Detailed application method and example of qserialport module for QT serial communication development


QT serial communication foundation and terminology description

The concept of serial communications is very simple. The serial port sends and receives bytes by bit. Although it is slower than parallel communication by byte, the serial port can use one line to send data and another line to receive data. It is very simple and can realize long-distance communication. For example, when IEEE488 defines the parallel traffic state, it stipulates that the total length of the equipment line shall not exceed 20m, and the length between any two equipment shall not exceed 2m;

For the serial port, the length can reach 1200 meters. Typically, a serial port is used for the transmission of ASCII characters. The communication is completed by three wires, namely ground wire, sending and receiving. Because the serial communication is asynchronous, the port can send data on one line and receive data on the other line. Other lines are used for handshake, but not necessary. The most important parameters of serial communication are baud rate, data bit, stop bit and parity. For two ports communicating, these parameters must match.

Baud rate:

This is a parameter to measure the symbol transmission rate. It refers to the change in unit time after the signal is modulated, that is, the number of carrier parameter changes in unit time. For example, 240 characters are transmitted per second, and each character format contains 10 bits (1 start bit, 1 stop bit and 8 data bits). At this time, the baud rate is 240bd, and the bit rate is 10 bits * 240 / S = 2400bps. Generally, the modulation rate is higher than baud rate, such as Manchester code. Typically, the baud rates of telephone lines are 1440028800 and 36600. The baud rate can be much greater than these values, but the baud rate is inversely proportional to the distance. High baud rate is often used for communication between instruments placed close to each other. A typical example is the communication of GPIB equipment.

Data bits:

This is a parameter that measures the actual data bits in communication. When a computer sends a packet, the actual data is often not 8 bits, and the standard values are 6, 7 and 8 bits. How you set it depends on the message you want to send. For example, the standard ascii code is 0 ~ 127 (7 bits). The extended ASCII code is 0 ~ 255 (8 bits). If the data uses simple text (standard ascii code), each packet uses 7 bits of data. Each packet refers to a byte, including start / stop bits, data bits and parity bits. Since the actual data bits depend on the selection of the communication protocol, the term “packet” refers to any communication situation.

Stop bit:

Used to represent the last bit of a single package. Typical values are 1, 1.5 and 2 bits. Because the data is timed on the transmission line and each device has its own clock, there may be a small synchronization between the two devices in the communication. Therefore, the stop bit not only indicates the end of transmission, but also provides an opportunity for the computer to correct clock synchronization. The more bits applicable to stop bits, the greater the tolerance of different clock synchronization, but the slower the data transmission rate.

Parity bit:

A simple error detection method in serial communication. There are four error detection methods: even, odd, high and low. Of course, it is OK to have no check bit. For even and odd parity, the serial port will set the parity bit (one bit after the data bit) and use a value to ensure that the transmitted data has even or odd logical high bits. For example, if the data is 011, for even parity, the parity bit is 0 to ensure that the number of digits with high logic is even. If it is an odd check, the check bit is 1, so there are three logical high bits. The high and low bits do not really check the data. Simply set the logic high or logic low check. In this way, the receiving device can know the state of one bit and have the opportunity to judge whether there is noise interfering with the communication or whether the transmission and reception data are not synchronized.

Introduction to QT serial communication module qtserialport

Qtserialport module is an additional module in Qt5, which provides a unified interface for hardware and virtual serial ports.

Because of its simplicity and reliability, serial port is still widely used in industries such as embedded system and robot. Using qtserialport module, developers can greatly shorten the cycle of developing serial port related applications.

QT serialport provides basic functions, including configuration, I / O operation, obtaining and setting the signal of RS-232 pin.

QT serialport module does not support the following features:

A. Characteristics of the terminal, such as echo, control Cr / LF, etc

B. Text mode

C. Timeout and latency configuration for read or write operations

D. When RS-232 pin signal change notification

To use qtserialport in an application, you need to include the following Declaration:

#include <QtSerialPort/QtSerialPort>

To link the qtserialport module, you need to add the following content to the. Pro file:

QT += serialport

Qserialport provides interface functions for accessing serial ports. Use the auxiliary class qserialportinfo to obtain the available serial port information. Take the qserialportinfo auxiliary class object as a parameter, and use the setport() or setportname() function to set the serial port device to be accessed.

After setting the port, you can use the open () function to open it in read-only, write only or read-write mode.

Note that the serial port is opened exclusively. Use the close() function to close the serial port and cancel the IO operation.

After the serial port is successfully opened, qserialport will try to determine the current configuration of the serial port and initialize it. Port settings can be reconfigured using the setbaudrate(), setdatabits(), setparity(), setstopbits(), and setflowcontrol() functions.

There is a pair of properties named qserialport:: dataterminalready, qserialport:: requesttosend

Qserialport provides a series of functions to abort the calling thread until the signal is triggered. These functions are used to block the serial port.

Waitforreadyread(): blocks the call until new data is readable

Waitforbyteswritten(): blocks the call until the data is written to the serial port

Blocking serial port programming is completely different from non blocking serial port programming. Blocking a serial port does not require a time cycle and usually simplifies the code. However, in Gui programs, in order to avoid freezing the user interface, blocking serial port programming can only be used for non GUI threads.

Qserialport can also use the stream operators of qtextstream and qdatastream. When trying to read using the stream operator > >, you need to ensure that there is enough data available.

QT serial communication module qserialport class member function

QSerialPort::QSerialPort(QObject *parent = Q_NULLPTR)
QSerialPort::QSerialPort(const QString &name, QObject *parent = Q_NULLPTR)
QSerialPort::QSerialPort(const QSerialPortInfo &serialPortInfo, QObject *parent = Q_NULLPTR)
//Returns true if no data is currently readable
[virtual] bool QSerialPort::atEnd() const
//After the baud rate changes, the signal is triggered
[signal] void QSerialPort::baudRateChanged(qint32 baudRate, QSerialPort::Directions directions)
//Returns the number of bytes of readable data
[virtual] qint64 QSerialPort::bytesAvailable() const
//Returns the number of bytes of writable data
[virtual] qint64 QSerialPort::bytesToWrite() const
//Close the serial port
[virtual] void QSerialPort::close()
//Set the serial port information to serialportinfo
void QSerialPort::setPort(const QSerialPortInfo &serialPortInfo)
//Set the serial port name to name
void QSerialPort::setPortName(const QString &name)

QT serial communication module qserialport simple serial port example

Main.cpp code

#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
 QApplication a(argc, argv);
 MainWindow w;;
 return a.exec();

Mainwindows. H code reference is as follows:

#include <QMainWindow>
#include <QtSerialPort/QSerialPort>
#include <QtSerialPort/QSerialPortInfo>
#include <QList>
#include <QDebug>
namespace Ui {
class MainWindow;
class MainWindow : public QMainWindow
 explicit MainWindow(QWidget *parent = 0);
private slots:
 void on_btn_openConsole_clicked();
 void on_btn_send_clicked();
 void on_btn_clearRecv_clicked();
 void on_btn_clearSend_clicked();
 void readData();
 Ui::MainWindow *ui;
 QSerialPort *serial;
#endif // MAINWINDOW_H

Mainwindows.cpp code

#include "mainwindow.h"
#include "ui_mainwindow.h"
static const char blankString[] = QT_TRANSLATE_NOOP("SettingsDialog", "N/A");
MainWindow::MainWindow(QWidget *parent) :
 ui(new Ui::MainWindow)
 serial = new QSerialPort;
 QString description;
 QString manufacturer;
 QString serialNumber;
 //Get available serial port
 QList<QSerialPortInfo> serialPortInfos = QSerialPortInfo::availablePorts();
 //Output the number of serial ports that can be used by the current system
 qDebug() << "Total numbers of ports: " << serialPortInfos.count();
 //Add all available serial port devices to ComboBox
 for (const QSerialPortInfo &serialPortInfo : serialPortInfos)
  QStringList list;
  description = serialPortInfo.description();
  manufacturer = serialPortInfo.manufacturer();
  serialNumber = serialPortInfo.serialNumber();
  list << serialPortInfo.portName()
    << (!description.isEmpty() ? description : blankString)
    << (!manufacturer.isEmpty() ? manufacturer : blankString)
    << (!serialNumber.isEmpty() ? serialNumber : blankString)
    << serialPortInfo.systemLocation()
    << (serialPortInfo.vendorIdentifier() ? QString::number(serialPortInfo.vendorIdentifier(), 16) : blankString)
    << (serialPortInfo.productIdentifier() ? QString::number(serialPortInfo.productIdentifier(), 16) : blankString);
  ui->comboBox_serialPort->addItem(list.first(), list);
 //Set baud rate
 ui->comboBox_baudRate->addItem(QStringLiteral("9600"), QSerialPort::Baud9600);
 ui->comboBox_baudRate->addItem(QStringLiteral("19200"), QSerialPort::Baud19200);
 ui->comboBox_baudRate->addItem(QStringLiteral("38400"), QSerialPort::Baud38400);
 ui->comboBox_baudRate->addItem(QStringLiteral("115200"), QSerialPort::Baud115200);
 //Set data bit
 ui->comboBox_dataBits->addItem(QStringLiteral("5"), QSerialPort::Data5);
 ui->comboBox_dataBits->addItem(QStringLiteral("6"), QSerialPort::Data6);
 ui->comboBox_dataBits->addItem(QStringLiteral("7"), QSerialPort::Data7);
 ui->comboBox_dataBits->addItem(QStringLiteral("8"), QSerialPort::Data8);
 //Set parity bit
 ui->comboBox_parity->addItem(tr("None"), QSerialPort::NoParity);
 ui->comboBox_parity->addItem(tr("Even"), QSerialPort::EvenParity);
 ui->comboBox_parity->addItem(tr("Odd"), QSerialPort::OddParity);
 ui->comboBox_parity->addItem(tr("Mark"), QSerialPort::MarkParity);
 ui->comboBox_parity->addItem(tr("Space"), QSerialPort::SpaceParity);
 //Set stop bit
 ui->comboBox_stopBit->addItem(QStringLiteral("1"), QSerialPort::OneStop);
 ui->comboBox_stopBit->addItem(QStringLiteral("2"), QSerialPort::TwoStop);
 //Add flow control
 ui->comboBox_flowBit->addItem(tr("None"), QSerialPort::NoFlowControl);
 ui->comboBox_flowBit->addItem(tr("RTS/CTS"), QSerialPort::HardwareControl);
 ui->comboBox_flowBit->addItem(tr("XON/XOFF"), QSerialPort::SoftwareControl);
 //Disable send button
 //delete serial;
 delete ui;
//Open serial port button slot function
void MainWindow::on_btn_openConsole_clicked()
 qDebug() << ui->btn_openConsole->text();
 if (ui->btn_ Openconsole - > text() = = tr ("open serial port"))
  //Set serial port name
  //Set baud rate
  //Set data bit
  //Set parity bit
  //Set stop bit
  //Set flow control
  //Open serial port
  if (serial->open(QIODevice::ReadWrite))
   ui->btn_ Openconsole - > settext (tr ("close serial port");
   //Correlation between signal and slot function
   connect(serial, &QSerialPort::readyRead, this, &MainWindow::readData);
  //Close the serial port
  //Restore setting function
  ui->btn_ Openconsole - > settext (tr ("open serial port");
//Send data slot function
void MainWindow::on_btn_send_clicked()
//Clear receive data slot function
void MainWindow::on_btn_clearRecv_clicked()
//Clear send area slot function
void MainWindow::on_btn_clearSend_clicked()
void MainWindow::readData()
 QByteArray buf;
 qDebug() << "readData: " << endl;
 buf = serial->readAll();
 if (!buf.isEmpty())
  QString str = ui->textEdit_recv->toPlainText();
  str += tr(buf);

Graphic interface design

The graphic interface design is shown in the figure:

Related attribute settings of graphical interface:

test result

The precondition is the support of serial port hardware

This paper mainly introduces the detailed use methods and examples of QT serial port communication module qserialport. For more knowledge and skills about QT serial port communication, please see the relevant links below

Recommended Today

Swift advanced (XV) extension

The extension in swift is somewhat similar to the category in OC Extension can beenumeration、structural morphology、class、agreementAdd new features□ you can add methods, calculation attributes, subscripts, (convenient) initializers, nested types, protocols, etc What extensions can’t do:□ original functions cannot be overwritten□ you cannot add storage attributes or add attribute observers to existing attributes□ cannot add parent […]