首页 > 其他分享 >QT做串口通信(串口助手)

QT做串口通信(串口助手)

时间:2023-02-22 16:11:59浏览次数:44  
标签:case ser comboBox QSerialPort break 助手 ui 串口 QT

QT做串口:

8e9e4c0273fb6b8fca8ba1e65faa9ee

main.cpp

#include "myserial.h"

#include <QApplication>

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

myserial.cpp

#include "myserial.h"
#include "ui_myserial.h"
#include <QDebug>

MySerial::MySerial(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::MySerial)
{
    ui->setupUi(this);

    //获取系统所有可用的串口
    foreach(const QSerialPortInfo &info,QSerialPortInfo::availablePorts()){
        qDebug()<<info.portName()<<info.description();
        //ui->comboBox_serialport->addItem(info.portName());
        QSerialPort serial(info);
        //测试串口是否可用
        if(serial.open(QIODevice::ReadWrite)){//空闲
            //将串口名加入选项列表
            ui->comboBox_serialport->addItem(serial.portName());
            //关闭串口
            serial.close();
        }
        else{//被占用
            ui->comboBox_serialport->addItem(serial.portName()+"(被占用)");
        }
    }

    ui->pushButton_send->setEnabled(false);
}

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

//打开/关闭串口
void MySerial::on_pushButton_openclose_clicked()
{
    if(ui->pushButton_openclose->text()=="打 开 串 口"){//打开
        ser = new QSerialPort(ui->comboBox_serialport->currentText(),this);
        //打开串口
        if(!ser->open(QIODevice::ReadWrite)){
            qDebug()<<"打开失败";
            ser->deleteLater();
            return;
        }

        //设置波特率
        switch (ui->comboBox_baudrate->currentIndex()) {
            case 0:
                ser->setBaudRate(QSerialPort::Baud2400);
                break;
            case 1:
                ser->setBaudRate(QSerialPort::Baud4800);
                break;
            case 2:
                ser->setBaudRate(QSerialPort::Baud9600);
                break;
            case 3:
                ser->setBaudRate(QSerialPort::Baud38400);
                break;
            case 4:
                ser->setBaudRate(QSerialPort::Baud115200);
                break;
        }

        //设置数据位位数
        switch (ui->comboBox_databits->currentIndex()) {
            case 0:
                ser->setDataBits(QSerialPort::Data5);
                break;
            case 1:
                ser->setDataBits(QSerialPort::Data6);
                break;
            case 2:
                ser->setDataBits(QSerialPort::Data7);
                break;
            case 3:
                ser->setDataBits(QSerialPort::Data8);
                break;
        }

        //设置校验位
        switch (ui->comboBox_parity->currentIndex()) {
            case 0:
                ser->setParity(QSerialPort::NoParity);
                break;
            case 1:
                ser->setParity(QSerialPort::OddParity);
                break;
            case 2:
                ser->setParity(QSerialPort::EvenParity);
                break;
        }

        //设置停止位
        switch (ui->comboBox_parity->currentIndex()) {
        case 0:
            ser->setStopBits(QSerialPort::OneStop);
            break;
        case 1:
            ser->setStopBits(QSerialPort::TwoStop);
            break;
        }

        //关闭流控
        ser->setFlowControl(QSerialPort::NoFlowControl);

        //关闭选项菜单
        ui->comboBox_parity->setEnabled(false);
        ui->comboBox_baudrate->setEnabled(false);
        ui->comboBox_databits->setEnabled(false);
        ui->comboBox_stopbits->setEnabled(false);
        ui->comboBox_serialport->setEnabled(false);
        ui->pushButton_send->setEnabled(true);

        //修改按钮显示
        ui->pushButton_openclose->setText("关 闭 串 口");

        //连接信号和槽
        QObject::connect(ser,&QSerialPort::readyRead,this,&MySerial::readData);
    }
    else{//关闭
        ser->clear();
        ser->close();
        ser->deleteLater();

        ui->comboBox_parity->setEnabled(true);
        ui->comboBox_baudrate->setEnabled(true);
        ui->comboBox_databits->setEnabled(true);
        ui->comboBox_stopbits->setEnabled(true);
        ui->comboBox_serialport->setEnabled(true);
        ui->pushButton_send->setEnabled(false);

        ui->pushButton_openclose->setText("打 开 串 口");

    }
}

//接收数据
void MySerial::readData()
{
    //接收所有数据
    QByteArray data = ser->readAll();

    if(!data.isEmpty()){
        ui->textBrowser->append(QString(data));
    }

    //data.clear();
}

//发送数据
void MySerial::on_pushButton_send_clicked()
{
    //获取要发送的数据
    QByteArray data = ui->textEdit->toPlainText().toUtf8();
    ser->write(data);
}

myserial.h

#ifndef MYSERIAL_H
#define MYSERIAL_H

#include <QWidget>
#include <QSerialPortInfo>
#include <QSerialPort>

QT_BEGIN_NAMESPACE
namespace Ui { class MySerial; }
QT_END_NAMESPACE

class MySerial : public QWidget
{
    Q_OBJECT

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

private slots:
    void on_pushButton_openclose_clicked();
    //接收串口数据槽函数
    void readData();

    void on_pushButton_send_clicked();

private:
    Ui::MySerial *ui;
    //串口类
    QSerialPort *ser;
};
#endif // MYSERIAL_H

4.5.6行的 #include问题 的解决方案:

https://blog.csdn.net/qq_52926110/article/details/122780655

mySerial.pro

QT       += core gui 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 \
    myserial.cpp

HEADERS += \
    myserial.h

FORMS += \
    myserial.ui

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

UI界面:

8e9e4c0273fb6b8fca8ba1e65faa9ee

1.

04651ee80ddff708b7fe0e784928bec

2.

efd0b2abafab49b0730080f58ceeba4

3.

5a41dd2f6abf5ba301e32df9c6cf494

4.

f8efe7fb8e6297b00f98c66be1dbc5b

5.

956452b02cfd2cee0da996d91de8d3a

6.

1705f0c5195f364323ed8f146fbd7e0

7.

5bbb4b35d37367f0fcf49c99a88894c

8.

17bdacec86af99adc3d4fcec88d7f6a

9.

aeca7097c234ade67456990cf2bc5b4

10.

c9f8b5830599e23736924fe77cd9cd9

11.

e5c690cb20aee70b87073d247e13353

12.

5365146641ea370c39629b2cc51d43b

8115157a95202927a38550e9d1f88d9

QT的新建工程文件部分:

最简单的结构:

main.cpp:

#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();
}

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

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

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

private:
    Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H

重点详解步骤:

mySerial.pro

qt串口这里需要用到一个很关键的类serialport,要现在.pro工程文件里面添加该模块(在QT += core gui 代码后面加上该模块)

.pro

QT       += core gui serialport

myserial.cpp

接下来,使用代码将串口号给加进去。打开“myserial.cpp文件”,对文件进行编写和修改。

#include "myserial.h"
#include "ui_myserial.h"
#include <QDebug>               /************************/

myserial::myserial(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::myserial)
{
    ui->setupUi(this);
      /******************获取系统所有可用的串口(后加的功能)*******************/
    //获取系统所有可用的串口
        foreach(const QSerialPortInfo &info,QSerialPortInfo::availablePorts()){
            qDebug()<<info.portName()<<info.description();
            //ui->comboBox_serialport->addItem(info.portName());
            QSerialPort serial(info);
            //测试串口是否可用
            if(serial.open(QIODevice::ReadWrite)){//空闲
                //将串口名加入选项列表
                ui->comboBox_serialport->addItem(serial.portName());
                //关闭串口
                serial.close();
            }
            else{//被占用
                ui->comboBox_serialport->addItem(serial.portName()+"(被占用)");
            }
        }

        ui->pushButton_send->setEnabled(false);
  /***************************************************************/
}

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

打开或者关闭串口功能(myserial.cpp)

/****************************打开/关闭串口***************************/
void myserial::on_pushButton_openclose_clicked()
{
    if(ui->pushButton_openclose->text()=="打 开 串 口"){//打开
        ser = new QSerialPort(ui->comboBox_serialport->currentText(),this);
        //打开串口
        if(!ser->open(QIODevice::ReadWrite)){
            qDebug()<<"打开失败";
            ser->deleteLater();
            return;
        }

        //设置波特率
        switch (ui->comboBox_baudrate->currentIndex()) {
            case 0:
                ser->setBaudRate(QSerialPort::Baud2400);
                break;
            case 1:
                ser->setBaudRate(QSerialPort::Baud4800);
                break;
            case 2:
                ser->setBaudRate(QSerialPort::Baud9600);
                break;
            case 3:
                ser->setBaudRate(QSerialPort::Baud38400);
                break;
            case 4:
                ser->setBaudRate(QSerialPort::Baud115200);
                break;
        }

        //设置数据位位数
        switch (ui->comboBox_databits->currentIndex()) {
            case 0:
                ser->setDataBits(QSerialPort::Data5);
                break;
            case 1:
                ser->setDataBits(QSerialPort::Data6);
                break;
            case 2:
                ser->setDataBits(QSerialPort::Data7);
                break;
            case 3:
                ser->setDataBits(QSerialPort::Data8);
                break;
        }

        //设置校验位
        switch (ui->comboBox_parity->currentIndex()) {
            case 0:
                ser->setParity(QSerialPort::NoParity);
                break;
            case 1:
                ser->setParity(QSerialPort::OddParity);
                break;
            case 2:
                ser->setParity(QSerialPort::EvenParity);
                break;
        }

        //设置停止位
        switch (ui->comboBox_parity->currentIndex()) {
        case 0:
            ser->setStopBits(QSerialPort::OneStop);
            break;
        case 1:
            ser->setStopBits(QSerialPort::TwoStop);
            break;
        }

        //关闭流控
        ser->setFlowControl(QSerialPort::NoFlowControl);

        //关闭选项菜单
        ui->comboBox_parity->setEnabled(false);
        ui->comboBox_baudrate->setEnabled(false);
        ui->comboBox_databits->setEnabled(false);
        ui->comboBox_stopbits->setEnabled(false);
        ui->comboBox_serialport->setEnabled(false);
        ui->pushButton_send->setEnabled(true);

        //修改按钮显示
        ui->pushButton_openclose->setText("关 闭 串 口");

        //连接信号和槽
        QObject::connect(ser,&QSerialPort::readyRead,this,&myserial::readData);
    }
    else{//关闭
        ser->clear();
        ser->close();
        ser->deleteLater();

        ui->comboBox_parity->setEnabled(true);
        ui->comboBox_baudrate->setEnabled(true);
        ui->comboBox_databits->setEnabled(true);
        ui->comboBox_stopbits->setEnabled(true);
        ui->comboBox_serialport->setEnabled(true);
        ui->pushButton_send->setEnabled(false);

        ui->pushButton_openclose->setText("打 开 串 口");

    }
}

接收数据功能(myserial.cpp)

//接收数据
void myserial::readData()
{
    //接收所有数据
    QByteArray data = ser->readAll();
    QString str = QString(data);

    if(!data.isEmpty()){
        ui->textBrowser->append(QString(str));
    }

    //data.clear();
}

发送数据功能(myserial.cpp)

//发送数据
void myserial::on_pushButton_send_clicked()
{
    //获取要发送的数据
    QByteArray data = ui->textEdit->toPlainText().toUtf8();
    ser->write(data);
}

标签:case,ser,comboBox,QSerialPort,break,助手,ui,串口,QT
From: https://www.cnblogs.com/L707/p/17144742.html

相关文章

  • 【PyQt5学习】02-PyQt5 库的结构
    1、pyqt5模块pyqt5模块(module)文档https://www.riverbankcomputing.com/static/Docs/PyQt5/module_index.htmlqtwidgets模块https://www.riverbankcomputing.com/static......
  • 【PyQt5学习】01-PyQt5 能做什么?要学什么?
    1、能做什么简单讲,就是用python做一个界面,表达你的想法或设计基于python语言的GUI工具库,用于开发小型的桌面应用,一些demo也可用于课程设计,用于呈现效果,如数字图像处理、......
  • Win10上模拟LoongArch虚拟机并搭建Qt5开发环境
    家里曾买了一台逸珑2F,也是龙芯cpu,然并非LoongArch架构。要尝鲜LoongArch的开发环境,只有虚拟机方案,qemu可以在x64win10上模拟LoongArch的虚拟机。一、软件准备1、下载QEM......
  • Qt调用摄像头一,基础版
     本示例,为纯Qt调用摄像头,功能比较简单,打开摄像头,设置参数,拍照涉及到的功能有:获取摄像头列表获取摄像头分辨率获取摄像头帧率获取摄像头支持的视频......
  • 小梅哥课程学习——串口通信的发送与调试(重在调试过程)
    1源代码2moduleuart_byte_tx(3clk,4reset_n,5data,6send_en,7baud_set,8uart_tx,9tx_done10);11......
  • 小梅哥课程学习——串口通信的发送与调试(重在调试过程)
    源代码moduleuart_byte_tx(clk,reset_n,data,send_en,baud_set,uart_tx,tx_done);inputclk;inputreset_n;inp......
  • Qt实现扇形图(2)
    #include"pieview.h"#include"mainwindow.h"#include<QtWidgets>MainWindow::MainWindow(QWidget*parent):QMainWindow(parent){QMenu*fileMenu=newQMenu(......
  • Qt音视频开发15-动态切换解码内核的设计
    一、前言动态切换解码内核这个需求也是源自客户的真实需求,既然是动态切换,那肯定是运行期间切换,而不是通过改变标志位重新编译程序来切换,最开始做的就是这种方式,这样就是实......
  • Hexo 助手 v1.0
    前言代替Gitbash方便快速部署hexo注意仅适用于Hexo部署工具Bat生成可执行程序,将bat放在Root目录下即可代码@echooffecho===========================echo说......
  • QT实现简单曲线图
    首先用到的控件为QGraphicsView使用到的头文件#include<QChart>#include<QChartView>#include<QtWidgets/QMainWindow>#include<QWidget>在QTPro文件当中需要添......