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短接

相关推荐
setmoon2141 分钟前
多协议网络库设计
开发语言·c++·算法
lsx2024063 分钟前
JavaScript 字符串模板
开发语言
2501_908329854 分钟前
嵌入式LinuxC++开发
开发语言·c++·算法
兑生4 分钟前
【灵神题单·贪心】1833. 雪糕的最大数量 | 排序贪心 | Java
java·开发语言
兑生8 分钟前
【灵神题单·贪心】3010. 将数组分成最小总代价的子数组 I | Java
java·开发语言·算法
Java面试题总结13 分钟前
go从零单排之方法
开发语言·后端·golang
Jay_Franklin14 分钟前
Python一站式科研工作流:从数据分析到报告生成
开发语言·python·论文笔记
小堃学编程15 分钟前
【项目实战】基于protobuf的发布订阅式消息队列(1)—— 准备工作
java·大数据·开发语言
setmoon21417 分钟前
C++中的构建器模式
开发语言·c++·算法
2301_8154829317 分钟前
C++中的桥接模式变体
开发语言·c++·算法