首页 > 其他分享 >QT学习第一战串口调试助手(3)实现收发数据以及显示

QT学习第一战串口调试助手(3)实现收发数据以及显示

时间:2024-10-16 16:17:16浏览次数:3  
标签:setEnabled QSerialPort QT comboBox 第一战 serialPort ui 串口

前情概述

在之前的文章中我们以及完成了串口调试助手页面的制作,

同时在打开串口按键的槽函数中实现串口的打开功能

本章节将注重于实现在串口打开后数据的收发问题以及一系列优化

本章流程

准备工作 

1.在头文件中定义以下变量

private slots:
    void on_btnCloseorOpenSerial_clicked();

    void on_btnSendContext_clicked();//发送按键的槽函数

    void on_SerialData_readyToRed();//接收信号的槽函数用于数据接收
private:
    Ui::Widget *ui;
    QSerialPort *serialPort;        //创建QSrialPort型指针
    int writeCntTotal;              //记录发送量
    int ReadCntTotal;               //记录接受量
    QString lastSend;               //判断发送的数据与上一次的数据是否相同
    bool serialStatus;              //判断串口是否打开的状态

2.在构造函数中初始化变量,将信号与槽连接

connect(serialPort, &QSerialPort::readyRead, this, &Widget::on_SerialData_readyToRed);

serialStatus = false;
writeCntTotal = 0;
ReadCntTotal = 0;
serialPort = new QSerialPort(this);    //实例化

发送按键功能

void Widget::on_btnSendContext_clicked()
{

    int writeCnt = 0;
//获取lineEdit中要发送的内容
    const char* sendData = ui->lineEditSendContext->text().toStdString().c_str();
//返回值为发送数量,若发送失败则返回-1
    writeCnt = serialPort->write(sendData);
//若发送成功
    if(writeCnt != -1)
    {
        writeCntTotal = writeCntTotal + writeCnt;
        qDebug()<<"send success"<<sendData;
        ui->labelSendStatus->setText("Send OK!");
        ui->labelSendcnt->setNum(writeCntTotal);
        if(strcmp(sendData, lastSend.toStdString().c_str()))  //比较字符串指针与QString
        {
            ui->textEditRecord->append(sendData);
            lastSend = QString(sendData);                     //转换
        }
    }
//若发送失败
    else
    {
        qDebug()<<"send fail";
        QMessageBox msgBox;
        msgBox.setText("串口未打开");
        msgBox.setWindowTitle("Error");
        msgBox.exec();
    }

}

接收数据功能

void Widget::on_SerialData_readyToRed()
{
    QString revMessage = serialPort->readAll();
    if(revMessage != NULL)
    {
        qDebug() << "GetMessage" << revMessage;
        ui->textEditRev->append(revMessage);
        ReadCntTotal = ReadCntTotal + revMessage.size();
        ui->labelRevcnt->setNum(ReadCntTotal);
    }
}

发送按键优化(优化内容见流程图)

void Widget::on_btnCloseorOpenSerial_clicked()
{
    if(serialStatus == false)
    {
        //1选择端口号
        serialPort->setPortName(ui->comboBox_serialNum->currentText());
        //2配置波特率
        serialPort->setBaudRate(ui->comboBox_baudrate->currentText().toInt());
        //3配置数据位
        serialPort->setDataBits(QSerialPort::DataBits(ui->comboBox_databit->currentText().toInt()));
        //4配置校验位
        switch (ui->comboBox_checkbit->currentIndex())
        {
        case 0:
            serialPort->setParity(QSerialPort::NoParity);
            break;
        case 1:
            serialPort->setParity(QSerialPort::EvenParity);
            break;
        case 2:
            serialPort->setParity(QSerialPort::MarkParity);
            break;
        case 3:
            serialPort->setParity(QSerialPort::OddParity);
            break;
        case 4:
            serialPort->setParity(QSerialPort::SpaceParity);
            break;
        default:
            serialPort->setParity(QSerialPort::UnknownParity);
            break;
        }
        //5配置停止位
        serialPort->setStopBits(QSerialPort::StopBits(ui->comboBox_stopbit->currentText().toInt()));
        //6流控
        if(ui->comboBox_fileCon->currentText() == "None")
        {
            serialPort->setFlowControl(QSerialPort::FlowControl(0));
        }
        //7打开串口
        if(serialPort->open(QIODevice::ReadWrite))
        {
            qDebug()<<ui->comboBox_serialNum->currentText()<<"open success";
            ui->comboBox_databit->setEnabled(false);
            ui->comboBox_fileCon->setEnabled(false);
            ui->comboBox_stopbit->setEnabled(false);
            ui->comboBox_baudrate->setEnabled(false);
            ui->comboBox_checkbit->setEnabled(false);
            ui->comboBox_serialNum->setEnabled(false);
            ui->btnCloseorOpenSerial->setText("关闭串口");
            serialStatus = true;
        }
        else
        {
            QMessageBox msgBox;
            msgBox.setText("打开失败,串口可能被占用");
            msgBox.setWindowTitle("串口错误");
            msgBox.exec();
        }
    }
    else
    {
        serialPort->close();                                //关闭串口
        ui->comboBox_databit->setEnabled(true);
        ui->comboBox_fileCon->setEnabled(true);
        ui->comboBox_stopbit->setEnabled(true);
        ui->comboBox_baudrate->setEnabled(true);
        ui->comboBox_checkbit->setEnabled(true);
        ui->comboBox_serialNum->setEnabled(true);
        ui->btnCloseorOpenSerial->setText("打开串口");
        serialStatus = false;
    }

}

标签:setEnabled,QSerialPort,QT,comboBox,第一战,serialPort,ui,串口
From: https://blog.csdn.net/qq_39465744/article/details/142964053

相关文章

  • Qt弹窗,点击非弹窗区域外,自动隐藏弹窗;
    //下面三个函数监听全局的隐藏事件,为了保证客户端不可见的时候日历隐藏boolCPlaybackCalendarWidget::eventFilter(QObject*watched,QEvent*eve){if(eve->type()==QEvent::ApplicationStateChange)//状态改变{if(qApp->a......
  • 基于RabbitMQ(windows)的MQTT(WSS)的安装配置和使用
    RabbitMQ官网地址https://www.rabbitmq.com/1.安装Erlang/OTP2.安装RabbitMQ3.开启后台管理rabbitmq-pluginsenablerabbitmq_managementhttp://127.0.0.1:15672/#/ 用户名密码默认guest4.开启mqttrabbitmq-pluginsenablerabbitmq_mqtt开启webmqttrabbitmq-pluginsenab......
  • QT打包exe(含错误解决方法)
    打包工具windeployqt.exe运行报错QT5core库链接有问题把打包工具路径下的libstdc++-6.dll文件粘贴到目标路径下(可以看到两个文件的大小是有差别的,具体原因未知)参考https://blog.csdn.net/hanhui22/article/details/109595193......
  • PyQt5 使用 Pyinstaller+multiprocessing 打包多进程应用时,引发的一些问题
    解决Pyinstaller打包PyQt5+multiprocessing多进程应用时,引发的一些问题,包括反复启动主进程,以及:AttributeError:'NoneType'objecthasnoattribute'write'本文提供一些解决方案,您可能需要根据自己的实际情况,逐个尝试,直到自己的multiprocessing多进程应用正常运行一、解决......
  • 串口HEX字节流交互协议解析库分享
    通信协议解析库说明一、概述用于上位机串口通讯协议解析,协议格式:AAlentypeiddata校验帧头(1byte)长度(1byte)协议类型(1byte)命令ID(1byte)数据(xbyte)校验和(1byte)AAxxxx异或校验和固定帧头:0xAA校验和:从AA到校验和之前的所有字节进行异或校验......
  • qt5报错无法枚举xxx字体:qt.qpa.fonts: Unable to enumerate family ' "WenYue XinQing
    问题描述:使用qt5时,出现错误提示:qt.qpa.fonts:Unabletoenumeratefamily'"WenYueXinQingNianTi(Non-CommercialUse)"'虽然不影响正常使用,但是还是希望解决。猜测:可能是qt5在自动枚举字体时,系统中安装的字体名称过长或其他参数不合规导致qt5无法枚举。如果此字体不是项......
  • QT实现改变窗口大小其子控件也自动调节大小
    创建一个顶层布局即可,一定要在MainWindows或者Widget的下面! 观察图标变化带有禁止的意思是分拆布局(当前无布局)现在是添加布局后了 注意:一定是在MainWindows或Widget才可以添加顶层布局,才可以实现控件自适应现在我想实现的是文字跟随变化,效果图如下所以我们利用......
  • QT的信号与槽
    提出疑问:界面上已经有的按键,怎么操作才能让用户按下按键后有操作上的反应呢?在Qt中,信号和槽机制是一种非常强大的事件通信机制。这是一个重要的概念,特别是对于初学者来说,理解它对于编写Qt程序至关重要。信号(Signals):是由对象在特定事件发生时发出的消息。例如,QPushButt......
  • MQTTnet.Server同时支持mqtt及websocket协议
    Net6后写法 Net6前写法Program.csusingMicrosoft.AspNetCore.Hosting;usingMicrosoft.Extensions.Configuration;usingMicrosoft.Extensions.Hosting;usingMQTTnet.AspNetCore;usingSystem;usingSystem.IO;namespaceMQTTnet.Server{publicclassProgra......
  • C# 实现串口通信
    usingSystem;usingSystem.IO.Ports;usingSystem.Linq;usingSystem.Text;usingSystem.Threading;namespaceDAL{publicclassAsySerialDal{privatestaticreadonlyobjectsyncRoot=newobject();constintCOMDAL_RECVBUF_SIZE......