Go Down

Topic: Do I really need delay() between Serial.read() statements? (Read 448 times) previous topic - next topic


Checking for the full number of characters may cause an error if one char gets dropped unexpectingly (small chance but still).

If you want to receive multiple bytes it is good practice to make a packet out of it with a start char and a stop char so you are allways capable of resync with the stream.

e.g.  stream = [123][456][789]

now you first read until you get a [ character (start of a packet)  and then you know you can read 3 chars (a,b,c) followed by the ] (end of packet)  
if that last one is indeed the ] you can be quite sure (still not 100%) that the 3 chars read are a b and c.
if you read an ] earlier it is possible that a char has been dropped e.g. [12]  (char 3 dropped)

If possible the start and stop character should not be part of the possible values a,b or c can take.

One step further is to add a checksum to every packet  ==> lets say the checksum function is the sum of chars modulo 10
then your packets could look like [1236] [4565] [7894]  (sum = 6, 15, 24 so checksum is resp.  6,5,4]
The goal of checksums is to see if bits have flipped during transport. Better checksums function are CRC8, CRC16 or CRC32.

Rob Tillaart

Nederlandse sectie - http://arduino.cc/forum/index.php/board,77.0.html -
(Please do not PM for private consultancy)

Go Up