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

相关推荐
番石榴AI几秒前
纯 CPU 推理!0.1B 超轻量级端到端OCR模型,使用 Java 进行文档解析
java·开发语言·ocr
likerhood3 分钟前
ConcurrentHashMap详细讲解(java)
java·开发语言·性能优化
机器学习之心18 分钟前
集成BWM法、熵权法、改进博弈论组合赋权与三角直觉模糊云模型的多属性评价模型,MATLAB代码
开发语言·matlab·熵权法·三角直觉模糊云模型·bwm法·改进博弈论组合赋权·多属性评价模型
特种加菲猫1 小时前
二叉搜索树:数据世界的“快速寻路指南”
开发语言·c++
特种加菲猫1 小时前
STL关联容器:Set/Multiset与Map/Multimap详解
开发语言·c++
我滴老baby1 小时前
0基础速通Python+AI|2026热门轻量化玩法全攻略:从入门到实战,3天搞定AI应用开发
开发语言·人工智能·python
一个天蝎座 白勺 程序猿1 小时前
Python(29)Python生成器函数深度解析:asyncio事件循环的底层实现与异步编程实战
开发语言·python
2zcode1 小时前
原创文档:基于MATLAB的线性预测编码变声器系统
开发语言·matlab·语音识别
七夜zippoe1 小时前
Python RESTful API设计终极指南:从理论到企业级实战
开发语言·python·http·pandas·restful api
lly2024061 小时前
Highcharts 配置说明
开发语言