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

Time:2021-7-30

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

//Constructor
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;
 w.show();
 return a.exec();
}

Mainwindows. H code reference is as follows:


#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QtSerialPort/QSerialPort>
#include <QtSerialPort/QSerialPortInfo>
#include <QList>
#include <QDebug>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
 Q_OBJECT
public:
 explicit MainWindow(QWidget *parent = 0);
 ~MainWindow();
private slots:
 void on_btn_openConsole_clicked();
 void on_btn_send_clicked();
 void on_btn_clearRecv_clicked();
 void on_btn_clearSend_clicked();
 void readData();
private:
 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) :
 QMainWindow(parent),
 ui(new Ui::MainWindow)
{
 ui->setupUi(this);
 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);
 }
 ui->comboBox_serialPort->addItem(tr("custom"));
 //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);
 ui->comboBox_baudRate->addItem(tr("Custom"));
 //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);
 ui->comboBox_dataBits->setCurrentIndex(3);
 //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
 ui->btn_send->setEnabled(false);
}
MainWindow::~MainWindow()
{
 //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
  serial->setPortName(ui->comboBox_serialPort->currentText());
  //Set baud rate
  serial->setBaudRate(ui->comboBox_baudRate->currentText().toInt());
  //Set data bit
  serial->setDataBits(QSerialPort::Data8);
  //Set parity bit
  serial->setParity(QSerialPort::NoParity);
  //Set stop bit
  serial->setStopBits(QSerialPort::OneStop);
  //Set flow control
  serial->setFlowControl(QSerialPort::NoFlowControl);
  //Open serial port
  if (serial->open(QIODevice::ReadWrite))
  {
   ui->comboBox_baudRate->setEnabled(false);
   ui->comboBox_dataBits->setEnabled(false);
   ui->comboBox_flowBit->setEnabled(false);
   ui->comboBox_parity->setEnabled(false);
   ui->comboBox_serialPort->setEnabled(false);
   ui->comboBox_stopBit->setEnabled(false);
   ui->btn_send->setEnabled(true);
   ui->btn_ Openconsole - > settext (tr ("close serial port");
   //Correlation between signal and slot function
   connect(serial, &QSerialPort::readyRead, this, &MainWindow::readData);
  }
 }
 else
 {
  //Close the serial port
  //serial->clear();
  serial->close();
  //serial->deleteLater();
  //Restore setting function
  ui->comboBox_baudRate->setEnabled(true);
  ui->comboBox_dataBits->setEnabled(true);
  ui->comboBox_flowBit->setEnabled(true);
  ui->comboBox_parity->setEnabled(true);
  ui->comboBox_serialPort->setEnabled(true);
  ui->comboBox_stopBit->setEnabled(true);
  ui->btn_ Openconsole - > settext (tr ("open serial port");
  ui->btn_send->setEnabled(false);
 }
}
//Send data slot function
void MainWindow::on_btn_send_clicked()
{
 serial->write(ui->textEdit_send->toPlainText().toLatin1());
}
//Clear receive data slot function
void MainWindow::on_btn_clearRecv_clicked()
{
 ui->textEdit_recv->clear();
}
//Clear send area slot function
void MainWindow::on_btn_clearSend_clicked()
{
 ui->textEdit_send->clear();
}
void MainWindow::readData()
{
 QByteArray buf;
 qDebug() << "readData: " << endl;
 buf = serial->readAll();
 if (!buf.isEmpty())
 {
  QString str = ui->textEdit_recv->toPlainText();
  str += tr(buf);
  ui->textEdit_recv->clear();
  ui->textEdit_recv->append(str);
 }
}

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 […]