PDA

View Full Version : problem reading the serial port



Eduardo Huerta
31st January 2020, 18:53
Hi, I have a problem with obtaining data through a serial port of an anemometer. The reading data is sent in three parts, that is, "\ x02" "4", "208110000026", "5 \ r" the number of elements in each QByteArray is variable. The first QbyteArray always has as the first element \ x02 "and the third QbyteArray always has the last element \ r. According to the manual, it should have for each serial port read a string as follows" \ x02 "" 42081100000265 \ r " I want to rebuild the string looking for the beginning of text "\ x02" and the end of text "\ r" but when reading the first element of the QBytearray that is "\ x02" I get an empty element. How can I find the "\ x02 "and" \ r "to be able to rebuild in a Qbytearray (" \ x02 "" 42081100000265 \ r ") and process the data in order to obtain the reading of the device?
Thanks for help me


void Widget::readSerialPort()
{
qDebug() << "Serial port read start";
QByteArray data=anemometerSerialPort->readAll();
qDebug() << data;//first reading ("\x02""4") , second reading"208110000026", third reading ("5\r").
qDebug() << data.at(0);//first reading ( ) , second reading (2), third reading (5).
qDebug() << "End of serial port reading";
repairDataString(data);
}

ChrisW67
31st January 2020, 21:13
The anemometer may send data that is three separate logical chunks, but what arrives at the other end (your end) is just a stream of bytes. You might receive each logical chunk all at once (as your code assumes), you might receive the entire packet all at once (possibly if the packets are short and far between), but in general you will get a few bytes at a time without regard for completeness or logical meaning.

If you want to read the stream of bytes and break that into several components then that is entirely up to your code to do.

A complete data structure seems to be this:
1. Two bytes "\x024" (hex 02 34)
2. A collection of ASCII characters of unknown length
3. Two bytes ''5\r" (hex 35 0d)

So, your code needs to read bytes as they arrive and add them to a buffer. When the bytes read includes a CR you have a potentially complete packet (or packets) in the buffer to process. You should process the buffer looking for the '\x02' (STX) and matching \r (CR), deal with those bytes, remove them from the buffer, and keep looking and dealing with for more complete packets, before returning to accumulating received bytes.

You would use the serial port readyRead() signal and a slot to accumulate bytes into a buffer (member variable) and look for CR, and another function to process a buffer for all complete packets when the CR is seen. The logic looks very like the same thing for a UDP socket, so those examples would be helpful.