作者:zzssdd2

E-mail:zzssdd2@foxmail.com

一、前言

开发环境:Qt5.12.10 + MinGW

实现的功能

  • 串口数据的接收
  • ascii字符形式显示与hex字符形式显示
  • 时间戳的显示
  • 接收数据的统计与显示
  • 接收清零

涉及的知识点

  • QSerialPort类的使用
  • 数据格式的转换
  • QTime类的使用
  • 控件QTextEditQCheckBoxQPushButtonQLabel的使用

二、功能实现

下面开始逐步讲解以上列举的功能实现

2.1、数据读取

《QT串口助手(二):参数配置》中已经实现了串口参数的配置,参数配置完成后就可以开启串口的数据接收功能了。在QT中的QSerialPort类继承自QIODevice类,所以可以使用QIODevice的readyRead()信号来触发数据的接收,在槽函数中实现数据的读取与处理。信号槽连接如下:

  1. /* 接收数据信号槽 */
  2. connect(serial, &QSerialPort::readyRead, this, &Widget::SerialPortReadyRead_slot);

补充:

[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.

当有收到新数据信号时,就会执行槽函数里面的数据读取功能:

  1. /*读取串口收到的数据*/
  2. QByteArray bytedata = serial->readAll();

补充:

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、数据转换

若需要将接收到的数据以HEX格式显示,则需要对接收到的数据进行以下处理:

  1. /*将数据转换为hex格式并以空格分隔->去掉头尾空白字符->转换为大写形式*/
  2. framedata = bytedata.toHex(' ').trimmed().toUpper();

补充:

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:

  1. QByteArray macAddress = QByteArray::fromHex("123456abcdef");
  2. macAddress.toHex(':'); // returns "12:34:56:ab:cd:ef"
  3. 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 returns true in the C locale. This includes the ASCII characters '\t', '\n', '\v', '\f', '\r', and ' '.

Example:

  1. QByteArray ba(" lots\t of\nwhitespace\r\n ");
  2. ba = ba.trimmed();
  3. // 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:

  1. QByteArray x("Qt by THE QT COMPANY");
  2. QByteArray y = x.toUpper();
  3. // y == "QT BY THE QT COMPANY"

2.3、添加时间戳

有时为了便于观察数据收发时间,需要在数据前插入时间戳显示。使用QTime类中的方法可以获取当前系统的时间(精确到ms),对数据处理如下:

  1. /*在数据前插入时间戳:[时:分:秒:毫秒]:RX -> 数据*/
  2. framedata = QString("[%1]:RX -> %2").arg(QTime::currentTime().toString("HH:mm:ss:zzz")).arg(framedata);

补充:

[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、接收计数

使用一个quint32类型数据对每次接收数据长度进行累加,记录接收数据总数,然后将数据更新到ui界面:

  1. dataTotalRx += bytedata.length();
  2. ui->RxCnt_label->setText(QString::number(dataTotalRx));

2.5、数据显示

以上功能完成后将数据显示到接收框中(为了区分不同显示格式,做了不同的颜色显示)。完整的数据接收功能展示如下:

  1. /*
  2. 函 数:SerialPortReadyRead_slot
  3. 描 述:readyRead()信号对应的数据接收槽函数
  4. 输 入:无
  5. 输 出:无
  6. */
  7. void Widget::SerialPortReadyRead_slot()
  8. {
  9. QString framedata;
  10. /*读取串口收到的数据*/
  11. QByteArray bytedata = serial->readAll();
  12. /*数据是否为空*/
  13. if (!bytedata.isEmpty())
  14. {
  15. if(ui->HexDisp_checkBox->isChecked())
  16. {
  17. /*hex显示*/
  18. framedata = bytedata.toHex(' ').trimmed().toUpper();
  19. ui->Receive_TextEdit->setTextColor(QColor(Qt::green));
  20. }
  21. else
  22. {
  23. /*ascii显示*/
  24. framedata = QString(bytedata);
  25. ui->Receive_TextEdit->setTextColor(QColor(Qt::magenta));
  26. }
  27. /*是否显示时间戳*/
  28. if (ui->TimeDisp_checkBox->isChecked())
  29. {
  30. framedata = QString("[%1]:RX -> %2").arg(QTime::currentTime().toString("HH:mm:ss:zzz")).arg(framedata);
  31. ui->Receive_TextEdit->append(framedata);
  32. }
  33. else
  34. {
  35. ui->Receive_TextEdit->insertPlainText(framedata);
  36. }
  37. /*更新接收计数*/
  38. dataTotalRxCnt += bytedata.length();
  39. ui->RxCnt_label->setText(QString::number(dataTotalRxCnt));
  40. }
  41. }

演示效果如下:

补充:

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、清除接收

清除接收按键点击后,会清除接收框显示的内容以及接收计数。使用QPushButton的点击信号槽实现如下:

  1. /*
  2. 函 数:on_ClearRx_Bt_clicked
  3. 描 述:清除接收按键点击信号对应的槽函数
  4. 输 入:无
  5. 输 出:无
  6. */
  7. void Widget::on_ClearRx_Bt_clicked()
  8. {
  9. ui->Receive_TextEdit->clear();
  10. ui->RxCnt_label->setText(QString::number(0));
  11. dataTotalRxCnt = 0;
  12. }

三、总结

本篇文章主要是讲述如何对串口数据进行接收和显示。除了上面列出的主要功能外,还需要了解各个控件的操作方法,比如QTextEdit文本的添加、QLabel文本的设置等。还有就是QT中基本的数据类型的数据使用,比如QStringQBytArray等。

QT串口助手(三):数据接收的更多相关文章

  1. QT串口助手(四):数据发送

    作者:zzssdd2 E-mail:zzssdd2@foxmail.com 一.前言 开发环境:Qt5.12.10 + MinGW 实现的功能 串口数据的发送 ascii字符与hex字符的相互转换 自 ...

  2. QT串口助手(五):文件操作

    作者:zzssdd2 E-mail:zzssdd2@foxmail.com 一.前言 开发环境:Qt5.12.10 + MinGW 功能 文件的发送 数据的保存 知识点 QFile类的使用 QTime ...

  3. QT串口助手(二):参数配置

    作者:zzssdd2 E-mail:zzssdd2@foxmail.com 一.前言 主要实现功能 串口参数的配置:波特率.数据位.停止位.校验位 本机串口设备的查询与添加显示 串口设备的手动更新与打 ...

  4. python串口助手

    最近项目中要使用模拟数据源通过向外发送数据,以前都是用C#编写,最近在研究python,所以就用python写了一个串口助手,方便以后的测试. 在电脑上通过虚拟串口助手产生两个虚拟串口,运行编写的串口 ...

  5. 玩转X-CTR100 | STM32F4 l X-Assistant串口助手控制功能

    我造轮子,你造车,创客一起造起来!塔克创新资讯[塔克社区 www.xtark.cn ][塔克博客 www.cnblogs.com/xtark/ ]      X-CTR100控制器配套的X-Assis ...

  6. 玩转X-CTR100 | X-Assistant串口助手控制功能

      更多塔克创新资讯欢迎登陆[塔克社区 www.xtark.cn ][塔克博客 www.cnblogs.com/xtark/ ]       X-CTR100控制器配套的X-Assistant串口调试 ...

  7. 【转】QT 串口QSerialPort + 解决接收数据不完整问题

    类:QSerialPort 例程:Examples\Qt-5.9.1\serialport\terminal,该例子完美展示了qt串口收发过程,直接在这上面修改就可以得到自己的串口软件.核心方法 // ...

  8. STM32移植RT-Thread后的串口在调试助手上出现:(mq != RT_NULL) assert failed at rt_mq_recv:2085和串口只发送数据不能接收数据问题

    STM32移植RT-Thread后的串口在调试助手上出现:(mq != RT_NULL) assert failed at rt_mq_recv:2085的问题讨论:http://www.rt-thr ...

  9. python3 Serial 串口助手的接收读取数据

    其实网上已经有许多python语言书写的串口,但大部分都是python2写的,没有找到一个合适的python编写的串口助手,只能自己来写一个串口助手,由于我只需要串口能够接收读取数据就可以了,故而这个 ...

随机推荐

  1. css进阶 00-准备

    前言 css 进阶的主要内容如下. #1.css 非布局样式 html 元素的分类和特性 css 选择器 css 常见属性(非布局样式) #2.css 布局相关 css 布局属性和组合解析 常见布局方 ...

  2. [水题日常]UVA1639 糖果(Candy,ACM/ICPC Chengdu 2012)

    今天来尝试了几道数学期望相关的题,这是我认为比较有趣的一道题 这次不废话啦直接开始~ 一句话题意:两个分别装有n个糖果的盒子,每次随机选一个盒子然后拿走一颗糖(选的概率分别是\(p\)和\((1-p) ...

  3. 个人微信公众号搭建Python实现 -开发配置和微信服务器转入-配置说明(14.1.2)

    @ 目录 1.查看基本配置 2.修改服务器配置 3.当上面都配置好,点击提交 4.配置如下 1.查看基本配置 登录到微信公众号控制面板后点击基本配置 这里要讲的就是订阅号 前往注册微信公众号 2.修改 ...

  4. 网络编程-python实现-TCP(1.1.3)

    @ 目录 1.TCP是什么 2.代码实现 1.TCP是什么 传输控制协议(TCP,Transmission Control Protocol)是一种面向连接的.可靠的.基于字节流的传输层通信协议,由I ...

  5. angular8 大地老师学习笔记---第九课

    父组件:news组件 <app-header [title]="title" [msg]="msg" [run]='run' [home]='this'& ...

  6. python scipy 求解简单线性方程组和fmin求函数最小值

    ###这是一个利用内置函数求最小值#####def func(x): return x ** 2 - 2 *x x = 1 func(x) opt.fmin(func ,x)## 用scipy求解线性 ...

  7. MySQL 存储函数的创建、调用、查找

    MySQL存储函数(自定义函数),函数一般用于计算和返回一个值,可以将经常需要使用的计算或功能写成一个函数 1.创建存储函数:使用 create function关键字 2.调用存储函数: 3.示例: ...

  8. 【linux】系统编程-2-消息队列

    目录 前言 4. 消息队列 4.1 概念 4.2 对比 4.3 函数及使用流程 4.3.1 msgget() 4.3.2 msgsng() 4.3.3 msgrcv() 4.3.4 msgctl() ...

  9. Mybatis 动态sql if 判读条件等于一个数字

    在Mybatis中 mapper中 boolean updateRegisterCompanyFlag(@Param(value = "companyId") String com ...

  10. Java学习日报9.30

    ********************************** double类型精度问题 ********************************** 1 package test; 2 ...