author :zzssdd2
E-mail:zzssdd2@foxmail.com
One 、 Preface
development environment :Qt5.12.10 + MinGW
Implemented function
- Receiving serial data
- ascii Character form display and hex Display in character form
- Time stamp display
- Statistics and display of received data
- Receive reset
Knowledge points involved
QSerialPort
The use of the class- Data format conversion
QTime
The use of the class- Control
QTextEdit
、QCheckBox
、QPushButton
、QLabel
Use
Two 、 Function realization
The following is a step-by-step explanation of the functions listed above
2.1、 data fetch
stay 《QT Serial assistant ( Two ): Parameter configuration 》 The configuration of serial port parameters has been realized in , After the parameter configuration is completed, the data receiving function of the serial port can be started . stay QT Medium QSerialPort Class inherits from QIODevice class , So you can use QIODevice Of readyRead() Signal to trigger the reception of data , Read and process data in slot function . The signal slot is connected as follows :
/* Receive data signal slot */
connect(serial, &QSerialPort::readyRead, this, &Widget::SerialPortReadyRead_slot);
Add :
[signal]
void QIODevice::readyRead()This signal is emitted once every time new data is available for reading from the device's current read channel. It will only be emitted again once new data is available, such as when a new payload of network data has arrived on your network socket, or when a new block of data has been appended to your device.
readyRead() is not emitted recursively; if you reenter the event loop or call waitForReadyRead() inside a slot connected to the readyRead() signal, the signal will not be reemitted (although waitForReadyRead() may still return true).
Note for developers implementing classes derived from QIODevice: you should always emit readyRead() when new data has arrived (do not emit it only because there's data still to be read in your buffers). Do not emit readyRead() in other conditions.
When a new data signal is received , It will perform the data reading function in the slot function :
/* Read the data received by the serial port */
QByteArray bytedata = serial->readAll();
Add :
QByteArray QIODevice::readAll()
Reads all remaining data from the device, and returns it as a byte array.
This function has no way of reporting errors; returning an empty QByteArray can mean either that no data was currently available for reading, or that an error occurred.
2.2、 Data conversion
If necessary, send the received data to HEX Format display , You need to process the received data as follows :
/* Convert data to hex Format and space -> Remove the leading and trailing white space -> Convert to uppercase */
framedata = bytedata.toHex(' ').trimmed().toUpper();
Add :
QByteArray QByteArray::toHex(char separator) const
This is an overloaded function.
Returns a hex encoded copy of the byte array. The hex encoding uses the numbers 0-9 and the letters a-f.
If separator is not '\0', the separator character is inserted between the hex bytes.
Example:
QByteArray macAddress = QByteArray::fromHex("123456abcdef"); macAddress.toHex(':'); // returns "12:34:56:ab:cd:ef" macAddress.toHex(0); // returns "123456abcdef"
This function was introduced in Qt 5.9.
QByteArray QByteArray::trimmed() const
Returns a byte array that has whitespace removed from the start and the end.
Whitespace means any character for which the standard C++
isspace()
function returnstrue
in the C locale. This includes the ASCII characters '\t', '\n', '\v', '\f', '\r', and ' '.Example:
QByteArray ba(" lots\t of\nwhitespace\r\n "); ba = ba.trimmed(); // ba == "lots\t of\nwhitespace";
Unlike simplified(), trimmed() leaves internal whitespace alone.
QByteArray QByteArray::toUpper() const
Returns an uppercase copy of the byte array. The bytearray is interpreted as a Latin-1 encoded string.
Example:
QByteArray x("Qt by THE QT COMPANY"); QByteArray y = x.toUpper(); // y == "QT BY THE QT COMPANY"
2.3、 Add time stamp
Sometimes, in order to observe the time of data sending and receiving , You need to insert a timestamp display before the data . Use QTime Class to get the time of the current system ( Accurate to ms), The data processing is as follows :
/* Insert a timestamp before the data :[ when : branch : second : millisecond ]:RX -> data */
framedata = QString("[%1]:RX -> %2").arg(QTime::currentTime().toString("HH:mm:ss:zzz")).arg(framedata);
Add :
[static]
QTime QTime::currentTime()Returns the current time as reported by the system clock.
Note that the accuracy depends on the accuracy of the underlying operating system; not all systems provide 1-millisecond accuracy.
Furthermore, currentTime() only increases within each day; it shall drop by 24 hours each time midnight passes; and, beside this, changes in it may not correspond to elapsed time, if a daylight-saving transition intervenes.
2.4、 Receive count
Use one quint32 Type data accumulates the length of each received data , Record the total number of received data , Then update the data to ui Interface :
dataTotalRx += bytedata.length();
ui->RxCnt_label->setText(QString::number(dataTotalRx));
2.5、 data display
After the above functions are completed, the data will be displayed in the receiving box ( To distinguish between different display formats , It's done in different colors ). The complete data receiving function is shown below :
/*
Letter Count :SerialPortReadyRead_slot
Sketch Statement :readyRead() The data receiving slot function corresponding to the signal
transport Enter into : nothing
transport Out : nothing
*/
void Widget::SerialPortReadyRead_slot()
{
QString framedata;
/* Read the data received by the serial port */
QByteArray bytedata = serial->readAll();
/* Is the data empty */
if (!bytedata.isEmpty())
{
if(ui->HexDisp_checkBox->isChecked())
{
/*hex Show */
framedata = bytedata.toHex(' ').trimmed().toUpper();
ui->Receive_TextEdit->setTextColor(QColor(Qt::green));
}
else
{
/*ascii Show */
framedata = QString(bytedata);
ui->Receive_TextEdit->setTextColor(QColor(Qt::magenta));
}
/* Whether to display the timestamp */
if (ui->TimeDisp_checkBox->isChecked())
{
framedata = QString("[%1]:RX -> %2").arg(QTime::currentTime().toString("HH:mm:ss:zzz")).arg(framedata);
ui->Receive_TextEdit->append(framedata);
}
else
{
ui->Receive_TextEdit->insertPlainText(framedata);
}
/* Update receive count */
dataTotalRxCnt += bytedata.length();
ui->RxCnt_label->setText(QString::number(dataTotalRxCnt));
}
}
The demonstration effect is as follows :
Add :
QColor::QColor(Qt::GlobalColor color)
This is an overloaded function.
Constructs a new color with a color value of color.
enum Qt::GlobalColor
Qt's predefined QColor objects:
Constant Value Description Qt::white
3
White (#ffffff) Qt::black
2
Black (#000000) Qt::red
7
Red (#ff0000) Qt::darkRed
13
Dark red (#800000) Qt::green
8
Green (#00ff00) Qt::darkGreen
14
Dark green (#008000) Qt::blue
9
Blue (#0000ff) Qt::darkBlue
15
Dark blue (#000080) Qt::cyan
10
Cyan (#00ffff) Qt::darkCyan
16
Dark cyan (#008080) Qt::magenta
11
Magenta (#ff00ff) Qt::darkMagenta
17
Dark magenta (#800080) Qt::yellow
12
Yellow (#ffff00) Qt::darkYellow
18
Dark yellow (#808000) Qt::gray
5
Gray (#a0a0a4) Qt::darkGray
4
Dark gray (#808080) Qt::lightGray
6
Light gray (#c0c0c0) Qt::transparent
19
a transparent black value (i.e., QColor(0, 0, 0, 0)) Qt::color0
0
0 pixel value (for bitmaps) Qt::color1
1
1 pixel value (for bitmaps)
2.6、 Clear receive
When Clear receive
Press the key and click , The contents displayed in the receive box and the receive count will be cleared . Use QPushButton The implementation of the click signal slot is as follows :
/*
Letter Count :on_ClearRx_Bt_clicked
Sketch Statement : Clear the slot function corresponding to the received button click signal
transport Enter into : nothing
transport Out : nothing
*/
void Widget::on_ClearRx_Bt_clicked()
{
ui->Receive_TextEdit->clear();
ui->RxCnt_label->setText(QString::number(0));
dataTotalRxCnt = 0;
}
3、 ... and 、 summary
This article is mainly about how to receive and display serial data . In addition to the main features listed above , You also need to know how to operate each control , such as QTextEdit The addition of text 、QLabel Text settings, etc . And that is QT Data usage of basic data types in , such as QString、QBytArray etc. .