Qt 5. QSerialPort串口收发

1. 代码
cpp 复制代码
//ex2.cpp
#include "ex2.h"
#include "ui_ex2.h"
#include <QtSerialPort/QSerialPort>
#include <QtSerialPort/QSerialPortInfo>

int static cnt = 0;

Ex2::Ex2(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::Ex2)
{
    ui->setupUi(this);

    //查找可用的串口
    foreach(const QSerialPortInfo &info, QSerialPortInfo::availablePorts())
    {
        QSerialPort serial;
        serial.setPort(info);
        if(serial.open(QIODevice::ReadWrite))
        {
            ui->comboBox_PortBox->addItem(serial.portName());
            serial.close();
        }
    }

    //设置波特率下拉菜单默认显示第三项
    ui->comboBox_BaudBox->addItem("2400");
    ui->comboBox_BaudBox->addItem("4800");
    ui->comboBox_BaudBox->addItem("9600");
    ui->comboBox_BaudBox->addItem("19200");
    ui->comboBox_BaudBox->addItem("115200");
    ui->comboBox_BaudBox->setCurrentIndex(0);
    //关闭发送按钮的使能
    ui->sendButton->setEnabled(false);
}

Ex2::~Ex2()
{
    delete ui;
}


void Ex2::on_pushButtonMy1_clicked()
{
    cnt ++;
    QString str = QString::number(cnt,10);
    ui->textEditMy1->setText(str);
}

void Ex2::on_pushButtonMy2_clicked()
{
    if(cnt > 0) cnt --;
    QString str = QString::number(cnt,10);
    ui->textEditMy1->setText(str);
}

void Ex2::on_pushButtonClr_clicked()
{
    ui->textEditMy1->clear();
}

void Ex2::on_pushButtonComm_clicked()
{
    QList<QSerialPortInfo> list = QSerialPortInfo::availablePorts();
    ui->textEditMy1->setText("Total number of availiable ports:" + QString::number(list.count(), 10));
    foreach(const QSerialPortInfo &serialportinfo, list)
    {
        ui->textEditMy1->append( "===========================================");
        ui->textEditMy1->append( "Port: " + serialportinfo.portName());
        ui->textEditMy1->append( "Location: " + serialportinfo.systemLocation());
        ui->textEditMy1->append( "Description: " + serialportinfo.description());
        ui->textEditMy1->append( "Manufactutor: " + serialportinfo.manufacturer());
        ui->textEditMy1->append( "Vendor Indentifier: " + QString::number(serialportinfo.vendorIdentifier(), 10));
        ui->textEditMy1->append( "Busy: " + QString::number(serialportinfo.isBusy()));
    }
}


//读取接收到的数据
void Ex2::Read_Data()
{
    QByteArray buf;
    buf = serial->readAll();
    if(!buf.isEmpty())
    {
        QString str = ui->textEditMy1->toPlainText();
        str+=tr(buf);
        ui->textEditMy1->clear();
        ui->textEditMy1->append(str);
    }
    buf.clear();
}


void Ex2::on_sendButton_clicked()
{
    serial->write(ui->textEditMy2->toPlainText().toLatin1());
}

void Ex2::on_openButton_clicked()
{
    if(ui->openButton->text()==tr("打开串口"))
    {
        serial = new QSerialPort;
        //设置串口名
        serial->setPortName(ui->comboBox_PortBox->currentText());
        //打开串口
        serial->open(QIODevice::ReadWrite);
        //设置波特率
        serial->setBaudRate(ui->comboBox_BaudBox->currentText().toInt());
        //设置数据位数
        serial->setDataBits(QSerialPort::Data8);
        //设置奇偶校验
        serial->setParity(QSerialPort::NoParity);
        //设置停止位
        serial->setStopBits(QSerialPort::OneStop);
        //设置流控制
        serial->setFlowControl(QSerialPort::NoFlowControl);
        //关闭设置菜单使能
        ui->comboBox_PortBox->setEnabled(false);
        ui->comboBox_BaudBox->setEnabled(false);
        ui->openButton->setText(tr("关闭串口"));
        ui->sendButton->setEnabled(true);
        //连接信号槽
        QObject::connect(serial, &QSerialPort::readyRead, this, &Ex2::Read_Data);
    }
    else
    {
        //关闭串口
        serial->clear();
        serial->close();
        serial->deleteLater();
        //恢复设置使能
        ui->comboBox_PortBox->setEnabled(true);
        ui->comboBox_BaudBox->setEnabled(true);
        ui->openButton->setText(tr("打开串口"));
        ui->sendButton->setEnabled(false);
    }
}

//main.cpp
#include "ex2.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Ex2 w;
    w.show();

    return a.exec();
}

//ex2.pro
//在ex2.pro 添加:QT += serialport
QT       += core gui

QT += serialport

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

CONFIG += c++11

# The following define makes your compiler emit warnings if you use
# any Qt feature that has been marked deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS

# You can also make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0

SOURCES += \
    main.cpp \
    ex2.cpp

HEADERS += \
    ex2.h

FORMS += \
    ex2.ui

# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target
2.效果

RX-TX短接

相关推荐
waicsdn_haha5 分钟前
Java/JDK下载、安装及环境配置超详细教程【Windows10、macOS和Linux图文详解】
java·运维·服务器·开发语言·windows·后端·jdk
_WndProc7 分钟前
C++ 日志输出
开发语言·c++·算法
qq_4335545416 分钟前
C++ 面向对象编程:+号运算符重载,左移运算符重载
开发语言·c++
数据小爬虫@35 分钟前
如何高效利用Python爬虫按关键字搜索苏宁商品
开发语言·爬虫·python
ZJ_.37 分钟前
WPSJS:让 WPS 办公与 JavaScript 完美联动
开发语言·前端·javascript·vscode·ecmascript·wps
Narutolxy43 分钟前
深入探讨 Go 中的高级表单验证与翻译:Gin 与 Validator 的实践之道20241223
开发语言·golang·gin
Hello.Reader1 小时前
全面解析 Golang Gin 框架
开发语言·golang·gin
禁默1 小时前
深入浅出:AWT的基本组件及其应用
java·开发语言·界面编程
Code哈哈笑1 小时前
【Java 学习】深度剖析Java多态:从向上转型到向下转型,解锁动态绑定的奥秘,让代码更优雅灵活
java·开发语言·学习
程序猿进阶1 小时前
深入解析 Spring WebFlux:原理与应用
java·开发语言·后端·spring·面试·架构·springboot