1
votes

How to read data on serial port in byte by byte fashion.

I have a source which sends out packets of varying packet size. I am reading the data in raw mode(non-canonical). When i set VMIN, i am able to get packet of that size or slightly larger. for ex: If the received packet size is 46 bytes, and if i set VMIN to say '1'. I receive the data in 2 chunks(meaning 2 read calls were needed to get the complete data with one fetching first 32 and next fetching the rest 14 bytes). If i set VMIN to 46, complete packet is fetched.

But the problem here is varying packet size. If the data packet size is more(say 70 bytes), it will mess up the buffer and following reads as it reads 60+ bytes in first read and rest in next read.

So i am thinking to read the data byte by byte and determine the end of the packet.

Does anyone know if it is do-able. Or any suggestion on how to read the complete data packet in one read operation.

UART setting: Baud: 115200 No parity. 1 stop bit. 8N1. No flow control.

Thanks in advance.

2
'So i am thinking to read the data byte by byte and determine the end of the packet' sure, that is certainly one protocol that should work, assuming you have an unambiguous end-of-packet marker byte.ThingyWotsit
I found something interesting here with the setting. pubs.opengroup.org/onlinepubs/7908799/xbd/termios.htmlsachin

2 Answers

0
votes

A good approach for for processing serial data is to Read chunks of data from port the into a buffer and then pull byte by byte from the buffer.

Serial port reading is affected by the timeout settings and incoming data flow, so the number of bytes per read are not guaranteed to be consistent. For example, if you knew that packets were always going to be 46 bytes, then you might think to set Vmin to 46 and expect to get 46 bytes per read. However, if the sending source sends multiple packets without delays between, then you might get all of one and part of another packet. If the sending source were to delay during the transmission of a packet for longer than the receiving port's timeout, then you would get fewer than Vmin bytes.

Be sure to code for the possibility of lost data. For example, let's say that packets start with and ends with . You start pulling data from the buffer and the first byte is , but 49 bytes later you encounter meaning a new packet, but without having seen the from the previous packet. There should of course also be a CRC for the packet, or at least a checksum.

0
votes

Since you are reading data that is structured into packets of variable size, you should add a 2 byte header for each packet and set it to the packet size.

In the reader you would read 2 bytes first and then decide how many bytes to read to receive the whole packet.