当前位置:网站首页>Software design and Development Notes 2: serial port debugging tool based on QT design
Software design and Development Notes 2: serial port debugging tool based on QT design
2022-06-23 05:44:00 【foxclever】
Serial communication is a problem we often encounter . Many times when we design a serial port application , We hope to have a simple 、 Visual way to verify it . In this article, we will base on QT Design a serial port debugging tool .
1、 summary
Before starting software design , Let's briefly analyze the main contents of such a small software . We believe that the software needs the following aspects :
- Configuration of serial port parameters , We hope that the serial port number can be automatically searched , We can select the corresponding configuration parameters .
- Input of sending data , For this software, we need to input the corresponding data to realize the sending of commands and messages , So we need to design the data input area and send interactive buttons .
- Display of received information , As a debugging tool , We certainly want to be able to see the message sent by the target device at a glance , So we need a display area to display the received area .
- Display of running status , We want to give feedback on the status of the operation to indicate whether the action of the operation is executed , So we need the status bar to implement this requirement .
- Other auxiliary functions , Also, send count 、 Receive count 、 Data storage and other functions are sometimes required , So let's consider it together .
There are many serial port tools on the Internet , The reason why we want to implement such a serial port debugging tool by ourselves , There are two main reasons . One is , The corresponding tools found on the internet sometimes a single tool can not fully meet our needs , So we design this tool according to our own needs, which can better meet our needs of serial port debugging . Two is , Through the implementation of such a tool , We can deepen our understanding of serial communication .
2、 Interface design
Based on the requirements analyzed in the previous section , Let's design the software interface first . We are QT Based on QMainWindow Class to generate an operation interface , Include menu bar 、 Toolbar and status bar to meet the requirements for status display and operation commands in the requirements .
And in the middle display area , We divide it into 3 That's ok 2 Column . Set from top to bottom in the left column : Serial port configuration operation area 、 Receive configuration area and send configuration area . Set from top to bottom in the right column : Dynamic curve display area 、 Information receiving display area and information sending input area . The specific interface settings are shown in the following figure :
After completing the layout as shown in the figure above , We can choose to configure the parameters of the space in the properties , You can also add related parameters to the code , I am used to doing it in code . After finishing the whole layout, we try to run the program , In normal operation, the following interface appears :
The above figure is the running interface after the layout is completed , But we haven't implemented the corresponding coding yet , Therefore, the functions proposed in the first section cannot be realized at present .
3、 coded
The next section , We will code and implement the corresponding functions in the future . We mainly divide the functions into parameter setting and operation functions 、 The function of data input and transmission and the function of data reception and display are realized .
3.1、 Parameter setting and operation function
The parameter configuration can be used directly except for the serial port number ComboBox Control . Serial port number , We want to search the serial port installed on the computer and add it to the control . The specific implementation is as follows :
// Search for available serial ports , And added to the serial port combo box
void MainWindow::SearchSerialPorts()
{
ui->comboBoxPort->clear();
foreach(const QSerialPortInfo &info,QSerialPortInfo::availablePorts())
{
ui->comboBoxPort->addItem(info.portName());
}
}
After configuring the serial port parameters , We can open the serial port to establish a connection . It should be noted that when we open the remote connection between serial ports , We need to establish a signal slot connection between the data receiving of the serial port and our data receiving and processing function . The specific implementation is as follows :
// Open the serial port
void MainWindow::on_actionConnect_triggered()
{
serialPort->setPortName(ui->comboBoxPort->currentText());
if(serialPort->open(QIODevice::ReadWrite)) // Open serial port successfully
{
serialPort->setBaudRate(ui->comboBoxBaud->currentText().toInt()); // set baud rate
switch(ui->comboBoxData->currentIndex()) // Set the number of data bits
{
case 1:serialPort->setDataBits(QSerialPort::Data8);break;
default: break;
}
switch(ui->comboBoxParity->currentIndex()) // Set parity
{
case 0: serialPort->setParity(QSerialPort::NoParity);break;
default: break;
}
switch(ui->comboBoxStop->currentIndex()) // Set stop bit
{
case 1: serialPort->setStopBits(QSerialPort::OneStop);break;
case 2: serialPort->setStopBits(QSerialPort::TwoStop);break;
default: break;
}
serialPort->setFlowControl(QSerialPort::NoFlowControl); // set flow control
// Connection slot function
QObject::connect(serialPort, &QSerialPort::readyRead, this, &MainWindow::ReadSerialData);
// Set whether the control can be used
ui->actionConnect->setEnabled(false);
ui->actionClose->setEnabled(true);
ui->actionRefresh->setEnabled(false);
}
else // Open failure prompt
{
QMessageBox::information(this,tr(" error "),tr(" Failed to open serial port !"),QMessageBox::Ok);
}
}
alike , In addition to opening the serial port to establish a connection , You also need to close the serial port and disconnect , The specific code is as follows :
// Turn off the serial port
void MainWindow::on_actionClose_triggered()
{
serialPort->clear();
serialPort->close();
// Set whether the control can be used
ui->actionConnect->setEnabled(true);
ui->actionClose->setEnabled(false);
ui->actionRefresh->setEnabled(true);
}
3.2、 Data input and transmission function
Data input and transmission , We designed 5 Bar command , Each command can be sent manually through the following buttons , It can also be sent automatically . When automatic circular transmission , Each selected command will be polled and sent at a set time interval .
First, let's take a look at the process of timing periodic transmission . We define a timer , Trigger the sending command with the time period we set , Send one command each time the check box is selected , Cycle in sequence until the cycle transmission is stopped manually . The specific code is as follows :
// Timed periodic transmission
void MainWindow::CycleSendData()
{
QCheckBox* cbSend;
while(true)
{
snIndex=snIndex>=6?1:snIndex;
cbSend=ui->groupBoxMessage->findChild<QCheckBox*>(QString("checkBoxSendEnable%1").arg(QString::number(snIndex)));
if(cbSend->isChecked())
{
WriteSerialData(snIndex);
snIndex++;
break;
}
snIndex++;
}
}
For manual single transmission, determine which button triggers the action, and then operate the corresponding data input box , Send the contents in the specified format . The specific operation code is as follows :
// Button triggers sending
void MainWindow::SingleSendData()
{
// Determine if the Sender yes QPushButton Is executed
if (QPushButton* btn = dynamic_cast<QPushButton*>(sender()))
{
QString senderName;
int sn=0;
senderName = btn->objectName();
sn = senderName.replace("pushButtonSend", "").toInt();
if((0<sn) && (sn<6))
{
WriteSerialData(sn);
}
}
}
3.3、 Data receiving and reality function
In our design , Receiving data is relatively simple . When the serial port receives data, it will trigger our receiving data processing function , And will be displayed in the format we set , The specific implementation code is as follows :
// Receive data from serial port
void MainWindow::ReadSerialData()
{
QByteArray rxDatas;
QString context;
rxDatas=serialPort->readAll();
if(!rxDatas.isNull())
{
if(ui->checkBoxRecieve->isChecked()) // Hexadecimal display
{
context = rxDatas.toHex(' ');
context=context.toUpper();
}
else //ASCII Show
{
context = rxDatas;
}
QString timeStrLine="["+QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss")+"][ receive ]: ";
context = timeStrLine+context+"\n\r";
QString content = "<span style=\" color:blue;\">"+context+"</span>";
ui->textBrowser->append(content);
receivedBytes=receivedBytes+rxDatas.size();
ui->lcdNumberRecieve->display(receivedBytes);
ui->statusbar->showMessage(tr(" Successfully read %1 Bytes of data ").arg(rxDatas.size()));
}
rxDatas.clear();
}
4、 Summary
After code debugging , Let's test the developed tool . First, we install a virtual serial port software to simulate the serial port we use for testing . If there is a hardware interface, it is best to , But there is no serial port on my computer , So we use virtual serial port to simulate a pair of serial ports . The specific configuration is shown in the figure below :
We use another serial port tool to realize communication verification with the tool we developed . We use access port To communicate with this tool .access port Use COM12,SerialMaster Use COM12, The corresponding serial port parameters are configured to be consistent . The specific configuration is shown in the figure below :
We use access port send data ,SerialMaster Received and displayed as blue characters in the display area . Again, we pass SerialMaster Send a message manually , Can be in access port See the corresponding data and in SerialMaster The display area of is displayed as red characters . As shown in the figure below :
Then we experimented with automatic cyclic transmission . We will send and get three command inputs , And select the corresponding check box as selected . And select the auto send checkbox , The corresponding command will be sent according to the set time interval . As shown in the figure below :
Here, the serial port debugging tool we want is basically implemented , Of course , In the future, we can also modify or add some functions to adapt to different applications , It can even be embedded in some applications to achieve the necessary testing functions . We publish the code to Gitee, Welcome to download and exchange .
Full code download address :https://gitee.com/ErichMoonan/serial-master
Welcome to your attention :

边栏推荐
- After the idea code is developed, the code is submitted. If the branch is found to be incorrect after submission, how can I withdraw it
- June 22, 2022: golang multiple choice question, what does the following golang code output? A:3; B:1; C:4; D: Compilation failed. package main import ( “fmt“ ) func mai
- 2022年中国重卡智能化升级专题研究
- Win11应用商店下载的软件怎么移到桌面
- Wechat applet: an artifact for calculating the full amount of orders
- C prime plus notes d'apprentissage - 2, constantes et formatage io (I / o)
- Jenkins installs and deploys and automatically builds and publishes jar applications
- Redis缓存穿透解决方案-布隆过滤器
- STM32cube CMSIS_ V2 FreeRTOS queue usage
- MySQL面试真题(二十六)——滴滴2020年笔试题
猜你喜欢

A bit of knowledge - folding forging and Damascus steel

Leetcode 797: all possible paths

SIFT feature point extraction

Management system of borrowed books based on SSM framework

Today's sleep quality record 80 points

Wechat applet: an artifact for calculating the full amount of orders

Visdom draws multiple dynamic loss curves

Database connection exception: create connection error, url: jdbc: mysql://ip/ Database name, errorcode 0, state 08s01 problem handling

STC 32比特8051單片機開發實例教程 一 開發環境搭建

jvm: 方法重载时,具体调用哪个方法,是由传入参数的静态类型来决定的,而不是由参数的实际类型来决定
随机推荐
Visdom draws multiple dynamic loss curves
C prime plus notes d'apprentissage - 2, constantes et formatage io (I / o)
AHA C language Chapter 8 game time is up (lesson 29)
数字藏品赋能实体产业释放了哪些利好?
Win11 app store keeps turning around solution
FS4059A与FS5080E充电芯片的区别
Wechat applet: wechat can also send flash photos to create wechat applet source code download and customize flash time
手机无线充电双线圈15W方案SOC英集芯IP6809
云原生数据库是未来数据库的天下
Real MySQL interview question (XXVIII) -- case - Analysis of indicators of communication operators
ArcTime 制作中英文字幕视频
Alibaba cloud object storage oss+picgo+typera implements the construction map
Opencv display image
技术开发团队视角看到的数字藏品机遇与挑战
啊哈C语言 第7章 有了它你能做更多的事(第27-28讲)
常用的无线充发射IC芯片
App automated test appium advanced
Implementation of MySQL custom sequence number
IP6809三线圈15W无线充电发射端方案ic英集芯
基于SSM框架的借阅图书管理系统