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 QTextEditQCheckBoxQPushButtonQLabel 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 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(), 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 QStringQBytArray etc. .

QT Serial assistant ( 3、 ... and ): More articles on data reception

  1. python Serial assistant

    In recent projects, we will use simulated data sources to send data out , Used to C# To write , Recent research python, So just use it. python Wrote a serial assistant , For future testing . Two virtual serial ports are generated by virtual serial port assistant on the computer , Run the prepared serial port ...

  2. Get along well with X-CTR100 | STM32F4 l X-Assistant Serial assistant control function

    I make wheels , You make cars , Makers build it together ! Tucker innovation news [ Tuck community www.xtark.cn ][ Tucker blog www.cnblogs.com/xtark/ ]      X-CTR100 The controller is equipped with X-Assis ...

  3. Get along well with X-CTR100 | X-Assistant Serial assistant control function

      Welcome to more Tucker innovation information [ Tuck community www.xtark.cn ][ Tucker blog www.cnblogs.com/xtark/ ]       X-CTR100 The controller is equipped with X-Assistant Serial debugging ...

  4. 【 turn 】QT A serial port QSerialPort + Solve the problem of incomplete received data

    class :QSerialPort routine :Examples\Qt-5.9.1\serialport\terminal, This example perfectly demonstrates qt Serial port transceiver process , You can get your own serial port software by modifying it directly . The core approach // ...

  5. STM32 transplant RT-Thread After the serial port appears in the debugging assistant :(mq != RT_NULL) assert failed at rt_mq_recv:2085 And serial port only send data, can't receive data

    STM32 transplant RT-Thread After the serial port appears in the debugging assistant :(mq != RT_NULL) assert failed at rt_mq_recv:2085 Discussion of the problem of :http://www.rt-thr ...

  6. python3 Serial The serial assistant receives and reads data

    In fact, there are many on the Internet python The serial port of language writing , But most of them are python2 Written , I didn't find a suitable one python Write the serial assistant , I can only write a serial assistant myself , Because I only need the serial port to receive and read data , So this ...

  7. Qt The solution of incomplete data received by serial communication

    When using serial port to receive data , When the amount of data is large, there will be incomplete data reception . Because the serial data acquisition function readAll() from readyRead() The signal triggers , but readyRead() The signal is sent immediately when the serial port reads the start flag , Does not ...

  8. Qt The solution of incomplete data received by serial communication ( Transfer pictures )

    When using serial port to receive data , When the amount of data is large, there will be incomplete data reception . Because the serial data acquisition function readAll() from readyRead() The signal triggers , but readyRead() The signal is sent immediately when the serial port reads the start flag , Does not ...

  9. Qt Small project serial assistant control LED

    Qt Small project serial assistant control LED Preface I just learned a little bit recently Qt Develop the upper computer , Try to do a small software training hands . Looking up a lot of information , Made a simple serial assistant , It can realize the basic sending and receiving function of serial port , Support Chinese display , It can also be controlled STM32 open ...

  10. Learn by writing serial assistant tools MFC The process ——( 3、 ... and )Unicode Wide character and multibyte character conversion of character set

    Learn by writing serial assistant tools MFC The process Because I've done it several times before MFC Programming for , Every time the project is finished ,MFC The basic operation is clear , But after a long time no longer contact MFC Project , Do it again MFC The project of , And get familiar with it from the beginning . This time by making a ...

Random recommendation

  1. Learn together android Custom control 3—— The edges are concave and convex View

    Preface Recently, when I was working on a project, I met the effect of a coupon , Because I feel that if I use pictures to do it, the adaptation effect is not good , Add your own customization view The knowledge in this field is relatively weak , So I want to try custom View To achieve . Let's look at the design effect first Implementation analysis above ...

  2. POJ 3261 Milk Patterns Find the suffix array A bunch of seeds The longest repeatable substring repeats at least k Time

    Milk Patterns   Description Farmer John has noticed that the quality of milk given by his cows varie ...

  3. stand-alone c1000k Connect

    stand-alone c1000k Connection means that a single machine realizes a million connections , The first thing to note is that connections are virtual and logical , The connection ends up in network card , A clear concept can help us come up with solutions to problems in a deeper and clearer way . Reference resources http://www.ideawu.net/blog ...

  4. java: cairo-misc.c:380: _cairo_operator_bounded_by_source: Assertion `NOT_REACHED' failed.

    Cause of error The question will be in Centos6.6 And later . It will also appear in other versions . Solution Ban carioGraphics > Add -Dorg.eclipse.swt.internal.gtk. ...

  5. senior I/O And readn and writen function

    The Conduit .FIFO And some equipment , Especially the terminal . The Internet and STREAMS There are two properties of the device : (1) once read The data returned by the operation may be less than the required data , Even if it doesn't reach the end of the file, it can be like this . It's not a mistake , We should continue to read ...

  6. asp.net in bin In the catalog dll.refresh file

    First of all, I found this article http://www.cnblogs.com/haokaibo/archive/2010/07/31/1789342.html Then find an English article http://monsur.xa ...

  7. Linux The meaning of some directory names in

    dig Linux An old abbreviation in English [2005-06-22 15:23][Nigel McFarlane][TechTarget] Unix There has been a 35 Years old . Many people think it started in the middle ages , The middle ages are relative to computers ...

  8. UOJ #278. 【UTR #2】 The order of the questions ( Sorting water problems )

    #278. [UTR #2] The order of the questions Drop a portal :http://uoj.ac/problem/278 describe “ Again .” Director of the universe problem center —— Jimido's on the subject, ski , Sit at your desk and plan for the coming U ...

  9. Idea Summary of common functions , Common skills at work

    1. Hide unused files such as IDEA Project configuration file for (.iml and .idea), open Settings-File Types, Add the file suffix to hide .  2. Common skills 2.1 adopt Alt+F8 Check the variable ...

  10. 3、 ... and )EasyUI layout

    Reference documents  http://www.jeasyui.com/documentation/layout.php