qt 操作串口

qt 操作串口


搭建工程
拷贝qextserialbase.cpp、qextserialbase.h、win_qextserialport.cpp和win_qextserialport.h到自己的工程下

//添加头文件
#include "win_qextserialport.h"
//添加串口定义
Win_QextSerialPort *Com;
//添加槽函数
private slots:
    void readCom(); //当接收到数据,会有信号
    void on_pushButton_clicked(); //发送按钮,产生信号

初始化

//定义串口对象,指定串口名和查询模式,这里使用事件驱动EventDriven
Com = new Win_QextSerialPort("COM2", QextSerialBase::EventDriven);

//以读写方式打开串口
if(Com->open(QIODevice::ReadWrite) == false)
{
    QMessageBox::warning(this, tr("warning"), tr("COM2 open failed."));
}

Com->setBaudRate(BAUD9600);
Com->setDataBits(DATA_8);
Com->setParity(PAR_NONE);
Com->setStopBits(STOP_1);
Com->setFlowControl(FLOW_OFF);

connect(Com,SIGNAL(readyRead()),this,SLOT(readCom()));
connect(button,SIGNAL(clicked()),this,SLOT(on_pushButton_clicked()));

void MainWindow::readCom()
{
    qDebug() << "read: "<< Com->bytesAvailable() << "bytes";

    //读取串口缓冲区的所有数据给临时变量data
    QByteArray data = Com->readAll();

    //将串口的数据显示在窗口的文本浏览器中
    ui->textBrowser->insertPlainText(data);
}

void MainWindow::on_pushButton_clicked() //发送数据
{
    //以ASCII码形式将数据写入串口
    Com->write(ui->lineEdit->text().toAscii());

    qDebug() << "write: "<< Com->bytesToWrite() << "bytes";
}

实际效果
qt 操作串口

经测试,在Win10运行,串口数据异常,还未找到原因
建议使用:https://blog.csdn.net/zhangxuechao_/article/details/81154296