qt5.14 串口助手

serialport.pro

QT += core gui
QT += serialport testlib
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

CONFIG += c++11
#CONFIG += console

# 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 \
    widget.cpp

HEADERS += \
    widget.h

FORMS += \
    widget.ui

# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target

widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QSerialPort>
#include <QSerialPortInfo>
#include <QDebug>
#include <QTextCodec>

QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE

class Widget : public QWidget
{
    Q_OBJECT

public:
    Widget(QWidget *parent = nullptr);
    ~Widget();

private slots:
    void on_pushButtonSearch_clicked();

    void on_pushButtonOpen_clicked();

    void on_pushButtonsend_clicked();

    void receiveInfo();

private:
    Ui::Widget *ui;
    QStringList m_portNameList;
    QStringList getPortNameList();
    QSerialPort *m_serialPort;


    void convertStringToHex(const QString &str, QByteArray &byteData);
    char convertCharToHex(char ch);
};
#endif // WIDGET_H

widget.cpp

#include "widget.h"
#include "ui_widget.h"

#include <iostream>
Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    m_serialPort = new QSerialPort;

    connect(m_serialPort,SIGNAL(readyRead()),this,SLOT(receiveInfo()));

}

Widget::~Widget()
{
    delete ui;
}

QStringList Widget::getPortNameList()
{
    QStringList m_serialPortName;
    foreach(const QSerialPortInfo &info,QSerialPortInfo::availablePorts())
    {
        m_serialPortName << info.portName();
        qDebug()<<"serialPortName:"<<info.portName();
    }
    return m_serialPortName;
}

void Widget::on_pushButtonSearch_clicked()
{
    m_portNameList = getPortNameList();
    ui->comboBox0->addItems(m_portNameList);
}

void Widget::on_pushButtonOpen_clicked()
{
    if (ui->pushButtonOpen->text()=="打开串口")
        {
            if(m_serialPort->isOpen())
            {
                m_serialPort->clear();
                m_serialPort->close();
            }

            m_serialPort->setPortName(m_portNameList[ui->comboBox0->currentIndex()]);

            if(!m_serialPort->open(QIODevice::ReadWrite))
            {
                qDebug()<<m_portNameList[ui->comboBox0->currentIndex()]<<"打开失败!";
                return;
            }

            //打开成功
            m_serialPort->setBaudRate(ui->comboBox1->currentText().toInt(),QSerialPort::AllDirections);//设置波特率和读写方向
            m_serialPort->setDataBits(QSerialPort::Data8);              //数据位为8位
            m_serialPort->setFlowControl(QSerialPort::NoFlowControl);   //无流控制
            m_serialPort->setParity(QSerialPort::NoParity);             //无校验位
            m_serialPort->setStopBits(QSerialPort::OneStop);            //一位停止位

            connect(m_serialPort,SIGNAL(readyRead()),this,SLOT(receiveInfo()));

            ui->pushButtonOpen->setText("关闭串口");
        } else
        {
            m_serialPort->close();
            ui->pushButtonOpen->setText("打开串口");
        }
}

void Widget::on_pushButtonsend_clicked()
{
    QString m_strSendData = ui->lineEditsend->text();

        if(ui->pushButtonsend->isChecked())
        {
            if (m_strSendData.contains(" "))
            {
                m_strSendData.replace(QString(" "),QString(""));    //把空格去掉
            }

            QByteArray sendBuf;

            convertStringToHex(m_strSendData, sendBuf);             //把QString 转换 为 hex

            m_serialPort->write(sendBuf);
        }
        else
        {
            m_serialPort->write(m_strSendData.toLocal8Bit());
        }
}

void Widget::convertStringToHex(const QString &str, QByteArray &byteData)
{
    int hexdata,lowhexdata;
    int hexdatalen = 0;
    int len = str.length();
    byteData.resize(len/2);
    char lstr,hstr;
    for(int i=0; i<len; )
    {
        //char lstr,
        hstr=str[i].toLatin1();
        if(hstr == ' ')
        {
            i++;
            continue;
        }
        i++;
        if(i >= len)
            break;
        lstr = str[i].toLatin1();
        hexdata = convertCharToHex(hstr);
        lowhexdata = convertCharToHex(lstr);
        if((hexdata == 16) || (lowhexdata == 16))
            break;
        else
            hexdata = hexdata*16+lowhexdata;
        i++;
        byteData[hexdatalen] = (char)hexdata;
        hexdatalen++;
    }
    byteData.resize(hexdatalen);
}


//-----------
char Widget::convertCharToHex(char ch)
{
    if((ch >= '0') && (ch <= '9'))
         return ch-0x30;
     else if((ch >= 'A') && (ch <= 'F'))
         return ch-'A'+10;
     else if((ch >= 'a') && (ch <= 'f'))
         return ch-'a'+10;
    else return (-1);
}

void Widget::receiveInfo()
{
    m_serialPort->waitForReadyRead(50);//阻塞函数
    QByteArray info = m_serialPort->readAll();
    std::cout<<std::string(info);
    QString strReceiveData = "";
    if(ui->radioButton1->isChecked())
    {
        QByteArray hexData = info.toHex();
        strReceiveData = hexData.toUpper();

        qDebug()<<"接收到串口数据: "<<strReceiveData;

        for(int i=0; i<strReceiveData.size(); i+=2+1)
            strReceiveData.insert(i, QLatin1String(" "));
        strReceiveData.remove(0, 1);

        qDebug()<<"处理后的串口数据: "<<strReceiveData;

        ui->textEditReceive->append(strReceiveData);
    }
    else
    {
        strReceiveData = QString(info);
        QTextCodec *tc = QTextCodec::codecForName("GBK");
        QString tmpQStr = tc->toUnicode(info);
        ui->textEditReceive->append(tmpQStr);
    }
    ui->textEditReceive->append("\r\n");
}

main.cpp

#include "widget.h"

#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Widget w;
    //w.show();
    return a.exec();
}

widget.ui

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>Widget</class>
 <widget class="QWidget" name="Widget">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>800</width>
    <height>600</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>Widget</string>
  </property>
  <layout class="QGridLayout" name="gridLayout">
   <item row="0" column="1">
    <layout class="QVBoxLayout" name="verticalLayout_2">
     <item>
      <widget class="QGroupBox" name="groupBox_3">
       <property name="title">
        <string>串口设置</string>
       </property>
       <layout class="QGridLayout" name="gridLayout_3">
        <item row="4" column="0">
         <widget class="QLabel" name="label_4">
          <property name="text">
           <string>检验位:</string>
          </property>
         </widget>
        </item>
        <item row="5" column="1">
         <widget class="QComboBox" name="comboBox4"/>
        </item>
        <item row="0" column="0">
         <widget class="QPushButton" name="pushButtonSearch">
          <property name="text">
           <string>搜索串口</string>
          </property>
         </widget>
        </item>
        <item row="0" column="1">
         <widget class="QPushButton" name="pushButtonOpen">
          <property name="text">
           <string>打开串口</string>
          </property>
         </widget>
        </item>
        <item row="2" column="1">
         <widget class="QComboBox" name="comboBox1">
          <item>
           <property name="text">
            <string>9600</string>
           </property>
          </item>
          <item>
           <property name="text">
            <string>115200</string>
           </property>
          </item>
         </widget>
        </item>
        <item row="1" column="1">
         <widget class="QComboBox" name="comboBox0"/>
        </item>
        <item row="2" column="0">
         <widget class="QLabel" name="label_2">
          <property name="text">
           <string>波特率:</string>
          </property>
         </widget>
        </item>
        <item row="4" column="1">
         <widget class="QComboBox" name="comboBox3"/>
        </item>
        <item row="3" column="1">
         <widget class="QComboBox" name="comboBox2"/>
        </item>
        <item row="1" column="0">
         <widget class="QLabel" name="label">
          <property name="text">
           <string>串口号:</string>
          </property>
         </widget>
        </item>
        <item row="3" column="0">
         <widget class="QLabel" name="label_3">
          <property name="text">
           <string>数据位:</string>
          </property>
         </widget>
        </item>
        <item row="6" column="1">
         <widget class="QComboBox" name="comboBox5"/>
        </item>
        <item row="5" column="0">
         <widget class="QLabel" name="label_5">
          <property name="text">
           <string>停止位:</string>
          </property>
         </widget>
        </item>
        <item row="6" column="0">
         <widget class="QLabel" name="label_6">
          <property name="text">
           <string>流控:</string>
          </property>
         </widget>
        </item>
       </layout>
      </widget>
     </item>
     <item>
      <widget class="QGroupBox" name="groupBox">
       <property name="title">
        <string>接收设置</string>
       </property>
       <layout class="QGridLayout" name="gridLayout_2">
        <item row="1" column="1">
         <widget class="QCheckBox" name="checkBox1">
          <property name="text">
           <string>显示发送</string>
          </property>
         </widget>
        </item>
        <item row="0" column="1">
         <widget class="QRadioButton" name="radioButton1">
          <property name="text">
           <string>Hex</string>
          </property>
         </widget>
        </item>
        <item row="0" column="0">
         <widget class="QRadioButton" name="radioButton0">
          <property name="text">
           <string>ASCII</string>
          </property>
          <property name="checked">
           <bool>true</bool>
          </property>
         </widget>
        </item>
        <item row="1" column="0">
         <widget class="QCheckBox" name="checkBox0">
          <property name="text">
           <string>自动换行</string>
          </property>
         </widget>
        </item>
        <item row="2" column="0">
         <widget class="QCheckBox" name="checkBox2">
          <property name="text">
           <string>显示时间</string>
          </property>
         </widget>
        </item>
        <item row="2" column="1">
         <widget class="QPushButton" name="pushButtonSave">
          <property name="text">
           <string>存入文件</string>
          </property>
         </widget>
        </item>
       </layout>
      </widget>
     </item>
     <item>
      <widget class="QGroupBox" name="groupBox_2">
       <property name="title">
        <string>发送设置</string>
       </property>
       <layout class="QGridLayout" name="gridLayout_4">
        <item row="0" column="1">
         <widget class="QRadioButton" name="radioButton3">
          <property name="text">
           <string>Hex</string>
          </property>
         </widget>
        </item>
        <item row="1" column="1">
         <widget class="QSpinBox" name="spinBox">
          <property name="suffix">
           <string>ms</string>
          </property>
          <property name="minimum">
           <number>1</number>
          </property>
          <property name="maximum">
           <number>1000</number>
          </property>
         </widget>
        </item>
        <item row="1" column="0">
         <widget class="QCheckBox" name="checkBox3">
          <property name="text">
           <string>自动重发</string>
          </property>
         </widget>
        </item>
        <item row="0" column="0">
         <widget class="QRadioButton" name="radioButton2">
          <property name="text">
           <string>ASCII</string>
          </property>
          <property name="checked">
           <bool>true</bool>
          </property>
         </widget>
        </item>
       </layout>
      </widget>
     </item>
     <item>
      <widget class="QPushButton" name="pushButtonsend">
       <property name="text">
        <string>发送</string>
       </property>
      </widget>
     </item>
    </layout>
   </item>
   <item row="0" column="0">
    <layout class="QHBoxLayout" name="horizontalLayout">
     <item>
      <layout class="QVBoxLayout" name="verticalLayout">
       <item>
        <widget class="QGroupBox" name="groupBox_5">
         <property name="title">
          <string>接收窗口</string>
         </property>
         <layout class="QHBoxLayout" name="horizontalLayout_2">
          <item>
           <widget class="QTextEdit" name="textEditReceive"/>
          </item>
         </layout>
        </widget>
       </item>
       <item>
        <widget class="QGroupBox" name="groupBox_4">
         <property name="title">
          <string>发送窗口</string>
         </property>
         <layout class="QHBoxLayout" name="horizontalLayout_3">
          <item>
           <widget class="QLineEdit" name="lineEditsend"/>
          </item>
         </layout>
        </widget>
       </item>
      </layout>
     </item>
    </layout>
   </item>
  </layout>
 </widget>
 <resources/>
 <connections/>
</ui>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 在Qt 5.14中,我们可以使用QSerialPort类来进行串口调试。首先,我们需要在项目文件中添加`QT += serialport`来包含SerialPort模块。 在代码中,我们可以先实例化一个QSerialPort对象,并设置串口的一些属性,例如端口号、波特率、校验位等。可以调用`setPortName()`来设置串口的名称,`setBaudRate()`设置波特率,`setParity()`设置校验位等。然后,我们可以使用open()函数打开串口。 接下来,我们可以通过`QSerialPort::readyRead()`信号来读取串口数据。可以将其与一个槽函数绑定,当有数据可读时触发该槽函数。在槽函数中,可以使用`readAll()`函数来读取所有可用的数据。 如果我们想要向串口发送数据,可以使用`write()`函数。我们可以将要发送的数据作为参数传递给该函数,它会将数据写入串口。 最后,在程序结束时,我们需要关闭串口。可以使用close()函数关闭串口连接。 总之,使用Qt 5.14进行串口调试可以通过QSerialPort类来实现。首先设置串口的属性,然后打开串口连接。当有数据可读时,使用readyRead()信号和相应的槽函数来读取数据。如果需要发送数据,可以使用write()函数发送。最后,在程序结束时,记得关闭串口。 ### 回答2: Qt5.14通过Qt Serial Port模块提供了串口调试的功能。使用该模块,可以方便地在Qt应用程序中与串口进行通信。 首先,需要在.pro文件中添加对serialport模块的引用: ``` QT += serialport ``` 然后,在代码中包含SerialPort类的头文件: ``` #include <QSerialPort> ``` 创建一个QSerialPort对象,并设置串口参数: ``` QSerialPort serial; serial.setPortName("COM1"); //设置串口名称,如COM1或/dev/ttyS0 serial.setBaudRate(QSerialPort::Baud115200); //设置波特率 serial.setDataBits(QSerialPort::Data8); //设置数据位 serial.setParity(QSerialPort::NoParity); //设置校验位 serial.setStopBits(QSerialPort::OneStop); //设置停止位 serial.setFlowControl(QSerialPort::NoFlowControl); //设置流控制 ``` 打开串口连接: ``` if(serial.open(QIODevice::ReadWrite)) { // 成功打开串口 // 进行通信操作 } else { // 打开串口失败 // 弹出错误提示等处理 } ``` 可以通过serial.write()函数发送数据: ``` QByteArray sendData = "Hello World"; serial.write(sendData); ``` 可以通过serial.read()函数接收数据: ``` QByteArray receiveData = serial.readAll(); ``` 关闭串口连接: ``` serial.close(); ``` 以上是一个基本的串口调试的示例,在实际使用中可以根据需求进行扩展和调整。需要注意的是,在使用QSerialPort之前,确保已经安装了相应的串口驱动程序。另外,在进行串口通信时,需要注意数据的传输格式,例如不同设备之间可能需要设置不同的波特率、数据位、停止位等。 ### 回答3: Qt5.14版本提供了一种方便的方式来进行串口调试。通过使用Qt提供的QSerialPort类,我们可以轻松地打开、读取和写入串口数据。 首先,在使用QSerialPort类之前,我们需要在Qt项目中包含QtSerialPort模块。在.pro文件中添加以下行: ```cpp QT += serialport ``` 接下来,我们可以在代码中创建一个QSerialPort对象,并设置串口的端口号、波特率以及其他通信参数。例如: ```cpp QSerialPort serial; serial.setPortName("COM1"); // 设置串口号 serial.setBaudRate(QSerialPort::Baud115200); // 设置波特率 serial.setDataBits(QSerialPort::Data8); // 设置数据位 serial.setParity(QSerialPort::NoParity); // 设置校验位 serial.setStopBits(QSerialPort::OneStop); // 设置停止位 serial.setFlowControl(QSerialPort::NoFlowControl); // 设置流控制 ``` 然后,我们可以使用`serial.open()`函数打开串口,并通过信号与槽来读取接收到的串口数据。例如,我们可以使用`serial.readyRead`信号槽来处理接收到的数据: ```cpp connect(&serial, &QSerialPort::readyRead, this, &MyClass::handleReadyRead); void MyClass::handleReadyRead() { QByteArray data = serial.readAll(); // 处理接收到的数据 } ``` 最后,我们可以使用`serial.write()`函数将数据写入串口。例如,可以使用如下代码将一个字符串写入串口: ```cpp QString message = "Hello, Serial!"; serial.write(message.toUtf8()); ``` 需要注意的是,在使用完串口之后,我们需要调用`serial.close()`函数来关闭串口。 以上就是使用Qt5.14进行串口调试的基本步骤。通过使用QSerialPort类和相关函数,我们可以方便地进行串口通信和调试。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值