当前位置:网站首页>QT serial port assistant (3): data receiving

QT serial port assistant (3): data receiving

2021-01-24 02:12:20 itread01

> author :zzssdd2>> E-mail: [email protected]# One 、 Foreword development environment :**Qt5.12.10 + MinGW**> Functions realized - Receiving serial port data - ascii Character form display and hex Character form display - Time stamp display - Statistics and display of received data - Receive reset > Knowledge points involved - `QSerialPort` Class - Data format conversion - `QTime` Class - Control element `QTextEdit`、`QCheckBox`、`QPushButton`、`QLabel` Use ![](https://img2020.cnblogs.com/blog/2193174/202101/2193174-20210123234501671-1437707537.png)# Two 、 Function realization the function realization listed above will be explained step by step ## 2.1、 The data is read in [《QT Serial port assistant ( Two ): Argument configuration 》](https://www.cnblogs.com/zzssdd2/p/14310882.html) The configuration of serial port arguments has been implemented in , After the argument is configured, you can start the data receiving function of the serial port . stay QT Medium *QSerialPort* Class inherits from *QIODevice* Class , So you can use QIODevice Of *readyRead()* Signal to trigger data reception , Read and process data in slot function . The signal slot is connected as follows :```c++/* Receiving 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](https://doc.qt.io/qt-5.12/qiodevice.html#waitForReadyRead)() inside a slot connected to the readyRead() signal, the signal will not be reemitted (although [waitForReadyRead](https://doc.qt.io/qt-5.12/qiodevice.html#waitForReadyRead)() may still return true).>> Note for developers implementing classes derived from [QIODevice](https://doc.qt.io/qt-5.12/qiodevice.html): 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 :```c++/* Read the data received by the serial port */QByteArray bytedata = serial->readAll();```> ** Add :**>> ### [QByteArray](https://doc.qt.io/qt-5.12/qbytearray.html) 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](https://doc.qt.io/qt-5.12/qbytearray.html) can mean either that no data was currently available for reading, or that an error occurred.## 2.2、 Data conversion if it is necessary to convert the received data to HEX Format display , You need to process the received data as follows :```c++/* Convert data to hex Format and space -> Remove the leading and trailing blanks -> Convert to uppercase */framedata = bytedata.toHex(' ').trimmed().toUpper();```> ** Add :**>> ### [QByteArray](https://doc.qt.io/qt-5.12/qbytearray.html#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](https://doc.qt.io/qt-5.12/qbytearray.html#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 returns `true` 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](https://doc.qt.io/qt-5.12/qbytearray.html#simplified)(), trimmed() leaves internal whitespace alone.>> ### [QByteArray](https://doc.qt.io/qt-5.12/qbytearray.html#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、 Time stamps are sometimes added to facilitate the observation of data sending and receiving time , You need to insert a time stamp before the data . Use *QTime* Class to get the time of the current system ( Accurate to ms), The data processing is as follows :```c++/* Insert a timestamp before the data :[ When : branch : second : millisecond ]:RX -> Information */framedata = QString("[%1]:RX -> %2").arg(QTime::currentTime().toString("HH:mm:ss:zzz")).arg(framedata);```> ** Add :**>> ### `[static]`[QTime](https://doc.qt.io/qt-5.12/qtime.html#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、 The receive count uses a *quint32* Type data accumulates the length of each received data , Record the total number of data received , Then update the data to ui Interface :```c++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 :```c++/* Letter Number :SerialPortReadyRead_slot Sketch Statement :readyRead() The data receiving slot function corresponding to the signal Lose Enter into : Nothing Lose Out : Nothing */void Widget::SerialPortReadyRead_slot(){ QString framedata; /* Read the data received by the serial port */ QByteArray bytedata = serial->readAll(); /* Whether the data is empty */ if (!bytedata.isEmpty()) { if(ui->HexDisp_checkBox->isChecked()) { /*hex Display */ framedata = bytedata.toHex(' ').trimmed().toUpper(); ui->Receive_TextEdit->setTextColor(QColor(Qt::green)); } else { /*ascii Display */ 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 :![](https://img2020.cnblogs.com/blog/2193174/202101/2193174-20210123234524403-2004902213.png)> ** Add :**>> ### QColor::QColor([Qt::GlobalColor](https://doc.qt.io/qt-5.12/qt.html#GlobalColor-enum) *color*)>> This is an overloaded function.>> Constructs a new color with a color value of *color*.>> ### enum Qt::GlobalColor>> Qt's predefined [QColor](https://doc.qt.io/qt-5.12/qcolor.html) 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](https://doc.qt.io/qt-5.12/qcolor.html)(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 to select , The contents displayed in the receive box and the receive count will be cleared . Use *QPushButton* The implementation of point select signal slot is as follows :```c++/* Letter Number :on_ClearRx_Bt_clicked Sketch Statement : Clear the slot function corresponding to the received keystroke signal Lose Enter into : Nothing Lose 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 port data . In addition to the main features listed above , You also need to know how to operate each control element , such as *QTextEdit* New words 、*QLabel* Text setting, etc . And then there's the QT Data usage of basic data types in , such as *QString*、*QBytArray

版权声明
本文为[itread01]所创,转载请带上原文链接,感谢
https://chowdera.com/2021/01/20210124021047762a.html

随机推荐