Qt serial port sending and receiving data

Posted by TitanKing on Thu, 30 Dec 2021 19:39:06 +0100

After several days of study, I finally wrote a host computer for serial communication. Let's start with the use of serial port class.

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

QT       += serialport

Then you can directly reference the header file.

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

QSerialPort: provides the function of accessing the serial port

QSerialPortInfo: provides information about the serial ports existing in the system

Next, you need to create a QSerialPort object, set the serial port name, baud rate, data bit, check bit, stop bit and other parameters, and then read and write the serial port.
It summarizes the process of setting, reading and writing.

1, Setting (example)

QSerialPort *serial = new QSerialPort;
//Set serial port name
serial->setPortName(name);
//Open serial port
serial->open(QIODevice::ReadWrite);
//set baud rate
serial->setBaudRate(BaudRate);
//Set the number of data bits
serial->setDataBits(QSerialPort::Data8);
 //Set parity
 serial->setParity(QSerialPort::NoParity);
//Set stop bit
serial->setStopBits(QSerialPort::OneStop);
//set flow control
serial->setFlowControl(QSerialPort::NoFlowControl);

The serial port name is set here (usually COM XX), open the serial port and set it to be 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 read and write. As a novice, if you don't know how to select keywords in QtCreator, press F1 to open the document and see the data of classes, functions, etc Book.

2, Read data

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

When the serial port receives the data and receives it, 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 into buf.

3, Send data

serial->write(data);  

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

Using the serial port only needs the above steps, and only needs to be executed after use

serial->close();

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

 

The code is as follows:

//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);
    //Find available serial ports
    foreach(const QSerialPortInfo &info, QSerialPortInfo::availablePorts())
    {
        QSerialPort serial;
        serial.setPort(info);
        if(serial.open(QIODevice::ReadWrite))
        {
            ui->PortBox->addItem(serial.portName());
            serial.close();
        }
    }
    //The setting baud rate drop-down menu displays the third item by default
    ui->BaudBox->setCurrentIndex(3);
    //Turn off the enable of the send button
    ui->sendButton->setEnabled(false);
    qDebug() << tr("The interface is set successfully!");
}
MainWindow::~MainWindow()
{
    delete ui;
}
//Empty acceptance window
void MainWindow::on_clearButton_clicked()
{
    ui->textEdit->clear();
}
//send data
void MainWindow::on_sendButton_clicked()
{
    serial->write(ui->textEdit_2->toPlainText().toLatin1());
}
//Read received data
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("Open serial port"))
    {
        serial = new QSerialPort;
        //Set serial port name
        serial->setPortName(ui->PortBox->currentText());
        //Open serial port
        serial->open(QIODevice::ReadWrite);
        //set baud rate
        serial->setBaudRate(ui->BaudBox->currentText().toInt());
        //Set the number of data bits
        switch(ui->BitNumBox->currentIndex())
        {
        case 8: serial->setDataBits(QSerialPort::Data8); break;
        default: break;
        }
        //Set parity
        switch(ui->ParityBox->currentIndex())
        {
        case 0: serial->setParity(QSerialPort::NoParity); break;
        default: break;
        }
        //Set stop bit
        switch(ui->StopBox->currentIndex())
        {
        case 1: serial->setStopBits(QSerialPort::OneStop); break;
        case 2: serial->setStopBits(QSerialPort::TwoStop); break;
        default: break;
        }
        //set flow control
        serial->setFlowControl(QSerialPort::NoFlowControl);
        //Turn off settings menu enable
        ui->PortBox->setEnabled(false);
        ui->BaudBox->setEnabled(false);
        ui->BitNumBox->setEnabled(false);
        ui->ParityBox->setEnabled(false);
        ui->StopBox->setEnabled(false);
        ui->openButton->setText(tr("Close the serial port"));
        ui->sendButton->setEnabled(true);
        //Connecting signal slot
        QObject::connect(serial, &QSerialPort::readyRead, this, &MainWindow::Read_Data);
    }
    else
    {
        //Close the serial port
        serial->clear();
        serial->close();
        serial->deleteLater();
        //Restore settings enable
        ui->PortBox->setEnabled(true);
        ui->BaudBox->setEnabled(true);
        ui->BitNumBox->setEnabled(true);
        ui->ParityBox->setEnabled(true);
        ui->StopBox->setEnabled(true);
        ui->openButton->setText(tr("Open serial port"));
        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();
}

 

Topics: Qt