当前位置:网站首页>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 # 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 :> ** 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
边栏推荐
- Thoughts on Ren Zhengfei's "Starlight does not ask passers-by"
- How do I learn to program?
- [high concurrency] how does readwritelock relate to caching?!
- 设置手机动态壁纸
- 恩怨纠缠的苹果和微信!苹果底层开源代码中包含兼容微信的代码,这是苹果偷学代码啦?
- Set mobile dynamic wallpaper
- Apple and wechat! The underlying open source code of Apple includes the code compatible with wechat. Is this the code that Apple learned secretly?
- 测试工程师的发展方向
- Development direction of Test Engineer
- 记录IDEA回退,远程库未回退问题
猜你喜欢
-
谁说中端存储无创新?Hitachi Vantara放了个大招.
-
Record the idea fallback and the remote library does not
-
Who says there is no innovation in midrange storage? Hitachi vantara made a big move
-
C语言: 部署开发环境 —— c语言学习计划第一天
-
C language: deploying development environment
-
高中语法_词法篇 动名词 动词不定式 现在分词与过去分词 独立主格结构 形容词和副词 冠词
-
Soul网关的数据注册和同步数据流探究
-
Lakehouse: 统一数据仓库和高级分析的新一代开放平台
-
特征预处理之归一化&标准化
-
High school grammar_ The present participle and the past participle of gerund infinitive in lexical discourse
随机推荐
- Research on data registration and synchronous data flow of soul gateway
- Lakehouse: a new open platform for unified data warehouse and advanced analysis
- Normalization and standardization of feature preprocessing
- Lakehouse: 统一数据仓库和高级分析的新一代开放平台
- 特征预处理之归一化&标准化
- Lakehouse: a new open platform for unified data warehouse and advanced analysis
- Normalization and standardization of feature preprocessing
- 9.软件包管理
- 9. Software package management
- 程序员如何写一份合格的简历?(附简历模版)
- 【Soul源码阅读-06】数据同步之websocket
- How do programmers write a qualified resume? (attach resume template)
- Websocket for data synchronization
- 【Soul源码阅读-09】数据同步之nacos
- Nacos for data synchronization
- 一種獲取context中keys和values的高效方法 | golang
- 如何在 Blazor WebAssembly中 使用 功能開關
- An efficient method to get keys and values in context
- 深入理解原子操作的本質
- How to use function switch in blazor webassembly
- 日常分享:關於時間複雜度和空間複雜度的一些優化心得分享(C#)
- Podinfo,迷你的 Go 微服務模板
- Deep understanding of the nature of atomic operations
- Daily sharing: some optimization experience sharing about time complexity and space complexity (c)
- Podinfo, mini go microservice template
- 聊聊cortex的tenant
- Talking about tenant of cortex
- 傲视Kubernetes(五):注解和命名空间
- Kubernetes (V): annotation and namespace
- maxwell电机转矩扫描与使用MTPA策略绘制效率map图
- Maxwell motor torque scanning and drawing efficiency map using MTPA strategy
- QT串口助手(三):数据接收
- QT serial assistant (3): data receiving
- QT串口助手(三):数据接收
- QT serial assistant (3): data receiving
- 技术基础 | Apache Cassandra 4.0基准测试
- 技术基础 | Apache Cassandra 4.0基准测试
- Technical foundation Apache Cassandra 4.0 benchmark
- Technical foundation Apache Cassandra 4.0 benchmark
- 草稿