Reading 15 bytes from serial port (one at a time or wait for all)

Hi,

I have an application that has to read 15 bytes into an array from the serial port every 10 seconds.

I see two approaches and would like to know if there are any pitfalls for either.

while (Serial.available()<14) {} 	// Wait 'till there are 15 Bytes waiting
for(int n=0; n<14; n++)
	statArray[n] = Serial.read(); 		// Get them.
  1. similar but read them as they are received instead of waiting for all.

On the surface it would seem to be no real difference, however there maybe issues I've not considered.

Thanks
John

Is there a terminating character?

It depends on your application. If it needs to wait, then either method is fine. But if your app needs to do something else in between, it better to read each piece when it's ready than waiting for whole thing because Serial is very slow.

Your first option will block the rest of your code till every thing is received.

By the way, your code snippet only reads 14 bytes :wink:

I think it is better to read singke bytes into a time out, like
Serial is available
Start timer
If I read a byte
{
Use the byte
Restart timer
}

Have a look at the examples in Serial Input Basics - simple reliable ways to receive data.

The problem with counting bytes is how is the Arduino supposed to know which is the first byte?

...R

Wow :slight_smile: A lot of good questions / suggestions.

I think each the responses is helpful.

The processor does have other things to do so if I keep the concept of reading all at once I will change the while to "if"

I know my data will not exceed 128. I was planning on the last byte to be something above 128.

My source sends the data in one "burst" every 10 seconds. The data will always be 15 bytes. This is the reason I considered waiting for all data in the first place. However I will add a verification the serial.available is 0 after I read the data.

And of course I will change the 14 to 15 to read all the bytes.

Thanks to all

John

Personally I prefer to use every single byte, like
I have a array of recived data and a index for that array.
In loop there is an if Serial available
In the if the index th part of array decame the Serial.read and the index increes.
If the index is egual to maximum+1 I call a fumction that use the array. I have all the message

If you know that he data stream will always be (at least) 14 bytes, instead of using while(Serial.available() < 14), which blocks, you can change that to if(Serial.available >= 14) and the loop the contents into an array. Not the preferred solution, but an option. Better to follow the advice already given and save the values into a buffer as they arrive. You'll still want to change out the while (blocking) statement and the count the bytes until all have arrived. Better yet if there is a terminating character on the data stream.