Although RS232 interface is no longer available on most household PC s. However, RS232 serial port is still widely used in industry because of its simple operation and reliable communication. In previous versions of Qt, there was no official support for RS232 serial port, so it was inconvenient to write serial port program. Now, QtSerialPort module is provided in Qt5.1, which is convenient for programmers to develop applications of serial port quickly. This article briefly talks about the use of QtSerialPort module.
The current QtSerialPort module provides two C++ classes, QSerialPort and QSerialPortInfo.
The QSerialPort class provides various interfaces for manipulating serial ports.
QSerial PortInfo is an auxiliary class that can provide various information about the available serial ports in a computer.
Usage method
First, the use of QSerial PortInfo is introduced. Here is a simple example to illustrate all serial devices on a computer.
First, you need to add the following to the pro file:
QT += serialport
The Cpp document is as follows:
The results on my computer are as follows:
Usually, we need to specify a program to use a certain serial port. At this time, we can not only use the serial name, because the serial name of the USB serial port may change every time it is inserted on different USB ports. At this time, you can use the serial number of the serial port, which is generally unique, such as the following code, first traverse all the serial ports, find the serial port we need, and then return.
QSerialPort is responsible for specific serial port operations. After choosing the serial port, the serial port should be opened before setting the baud rate and other parameters. These parameters are set up and can be used. The most basic operations are read() and write(). It should be noted that both operations are non-blocking.
Another important signal that needs to be used is void QIODevice::readyRead()
Each time the serial port receives data, it sends out this signal. We need to define a slot in our program and connect it to this signal. In this way, every time new data arrives, we can read data in slot. At this time, we must read all the data in the serial buffer, which can be realized by readAll().
The following code snippet gives an example of setting up a serial port.