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

相关推荐
q5673152321 分钟前
在 Bash 中获取 Python 模块变量列
开发语言·python·bash
许野平1 小时前
Rust: 利用 chrono 库实现日期和字符串互相转换
开发语言·后端·rust·字符串·转换·日期·chrono
也无晴也无风雨1 小时前
在JS中, 0 == [0] 吗
开发语言·javascript
狂奔solar1 小时前
yelp数据集上识别潜在的热门商家
开发语言·python
blammmp2 小时前
Java:数据结构-枚举
java·开发语言·数据结构
何曾参静谧2 小时前
「C/C++」C/C++ 指针篇 之 指针运算
c语言·开发语言·c++
暗黑起源喵2 小时前
设计模式-工厂设计模式
java·开发语言·设计模式
WaaTong2 小时前
Java反射
java·开发语言·反射
Troc_wangpeng2 小时前
R language 关于二维平面直角坐标系的制作
开发语言·机器学习
努力的家伙是不讨厌的2 小时前
解析json导出csv或者直接入库
开发语言·python·json