Qt serial port to send and receive data

The following begins to introduce the use of the serial port class.

First of all, QT5 comes with the QSerialPort class. When using it, you need to add a line in the pro file:

QT       += serialport

Then directly refer to the header file and you can use it.

#include <QtSerialPort/QSerialPort>  
#include <QtSerialPort/QSerialPortInfo>

QSerialPort: Provides access to serial ports

QSerialPortInfo: Provides information about the serial ports that exist in the system

Next, you need to create a QSerialPort object, set the serial port name, baud rate, data bits, parity bits, stop bits and other parameters, and then perform serial port read and write operations.
It roughly summed up the process of setting, reading and writing.

The benefits of this article, free to receive Qt development learning materials package, technical video, including (Qt actual combat project, C++ language foundation, C++ design mode, introduction to Qt programming, QT signal and slot mechanism, QT interface development-image drawing, QT network, QT database programming, QT project combat, QSS, OpenCV, Quick module, interview questions, etc.) ↓↓↓↓↓↓See below↓↓Click on the bottom of the article to receive the fee↓↓

1. Settings (example)

QSerialPort *serial = new QSerialPort;
//设置串口名
serial->setPortName(name);
//打开串口
serial->open(QIODevice::ReadWrite);
//设置波特率
serial->setBaudRate(BaudRate);
//设置数据位数
serial->setDataBits(QSerialPort::Data8);
 //设置奇偶校验
 serial->setParity(QSerialPort::NoParity);
//设置停止位
serial->setStopBits(QSerialPort::OneStop);
//设置流控制
serial->setFlowControl(QSerialPort::NoFlowControl);

Here set the name of the serial port, open the serial port and set it as readable and writable, the baud rate is BaudRate, the data bit is 8 bits, there is no parity bit, the stop bit is 1 bit, and there is no flow control. After setting these, you can perform read and write operations. As a novice, I found that I didn't know how to select keywords in QtCreator, press F1 to open the document to see the manual of classes, functions and other data.

2. Read data

void MainWindow::Read_Data()
{
    QByteArray buf;
    buf = serial->readAll();
}

When the serial port receives data and completes the reception, it will send a readyRead() signal, so you only need to write a slot function Read_Data(), set the signal slot, and use readAll() in the slot function to read the received data to in buf.

3. Send data

serial->write(data);  

Use the write function to send the string data byte by byte.

Only the above steps are needed to use the serial port, and only need to execute after use

serial->close();

You can close the serial port. I used the ui interface design to write the upper computer, the interface is as follows:

 

code show as below:

//mianwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QDebug>
#include <QtSerialPort/QSerialPort>
#include <QtSerialPort/QSerialPortInfo>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
    Q_OBJECT
public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
private slots:
    void on_clearButton_clicked();
    void on_sendButton_clicked();
    void on_openButton_clicked();
    void Read_Data();
private:
    Ui::MainWindow *ui;
    QSerialPort *serial;
};
#endif // MAINWINDOW_H
//mainwindow.c
#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    //查找可用的串口
    foreach(const QSerialPortInfo &info, QSerialPortInfo::availablePorts())
    {
        QSerialPort serial;
        serial.setPort(info);
        if(serial.open(QIODevice::ReadWrite))
        {
            ui->PortBox->addItem(serial.portName());
            serial.close();
        }
    }
    //设置波特率下拉菜单默认显示第三项
    ui->BaudBox->setCurrentIndex(3);
    //关闭发送按钮的使能
    ui->sendButton->setEnabled(false);
    qDebug() << tr("界面设定成功!");
}
MainWindow::~MainWindow()
{
    delete ui;
}
//清空接受窗口
void MainWindow::on_clearButton_clicked()
{
    ui->textEdit->clear();
}
//发送数据
void MainWindow::on_sendButton_clicked()
{
    serial->write(ui->textEdit_2->toPlainText().toLatin1());
}
//读取接收到的数据
void MainWindow::Read_Data()
{
    QByteArray buf;
    buf = serial->readAll();
    if(!buf.isEmpty())
    {
        QString str = ui->textEdit->toPlainText();
        str+=tr(buf);
        ui->textEdit->clear();
        ui->textEdit->append(str);
    }
    buf.clear();
}
void MainWindow::on_openButton_clicked()
{
    if(ui->openButton->text()==tr("打开串口"))
    {
        serial = new QSerialPort;
        //设置串口名
        serial->setPortName(ui->PortBox->currentText());
        //打开串口
        serial->open(QIODevice::ReadWrite);
        //设置波特率
        serial->setBaudRate(ui->BaudBox->currentText().toInt());
        //设置数据位数
        switch(ui->BitNumBox->currentIndex())
        {
        case 8: serial->setDataBits(QSerialPort::Data8); break;
        default: break;
        }
        //设置奇偶校验
        switch(ui->ParityBox->currentIndex())
        {
        case 0: serial->setParity(QSerialPort::NoParity); break;
        default: break;
        }
        //设置停止位
        switch(ui->StopBox->currentIndex())
        {
        case 1: serial->setStopBits(QSerialPort::OneStop); break;
        case 2: serial->setStopBits(QSerialPort::TwoStop); break;
        default: break;
        }
        //设置流控制
        serial->setFlowControl(QSerialPort::NoFlowControl);
        //关闭设置菜单使能
        ui->PortBox->setEnabled(false);
        ui->BaudBox->setEnabled(false);
        ui->BitNumBox->setEnabled(false);
        ui->ParityBox->setEnabled(false);
        ui->StopBox->setEnabled(false);
        ui->openButton->setText(tr("关闭串口"));
        ui->sendButton->setEnabled(true);
        //连接信号槽
        QObject::connect(serial, &QSerialPort::readyRead, this, &MainWindow::Read_Data);
    }
    else
    {
        //关闭串口
        serial->clear();
        serial->close();
        serial->deleteLater();
        //恢复设置使能
        ui->PortBox->setEnabled(true);
        ui->BaudBox->setEnabled(true);
        ui->BitNumBox->setEnabled(true);
        ui->ParityBox->setEnabled(true);
        ui->StopBox->setEnabled(true);
        ui->openButton->setText(tr("打开串口"));
        ui->sendButton->setEnabled(false);
    }
}
//main.c
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    return a.exec();
}

The benefits of this article, free to receive Qt development learning materials package, technical video, including (Qt actual combat project, C++ language foundation, C++ design mode, introduction to Qt programming, QT signal and slot mechanism, QT interface development-image drawing, QT network, QT database programming, QT project combat, QSS, OpenCV, Quick module, interview questions, etc.) ↓↓↓↓↓↓See below↓↓Click on the bottom of the article to receive the fee↓↓

Guess you like

Origin blog.csdn.net/m0_73443478/article/details/132188625
Recommended