Doesn’t available() just return the number of bytes available now, which might only be 1. You need an outer loop to keep trying to read till all the 9 bytes have been acquired? Something like:
int bytes_read = 0 ;
while (bytes_read < 9)
{
if (Serial.available() > 0)
{
...... read a byte and store it ....
bytes_read ++;
}
}
Or you could wait for available() to return at least 9 before reading all 9 - the hardware buffer is 128 bytes.
int availableBytes = Serial.available();
delay(2000);
Two seconds is a very long time to wait.
If your serial line is running constantly at 9600 baud, the serial receiver buffer would overflow in less than a fifth of a second.
One thing always to keep in mind when writing this kind of code is to be able to handle things when something goes wrong – like what if you never get the 9 bytes you are expecting? I doubt you would want your code to lock up.
I’d probably do something like this:
#define MAX_MILLIS_TO_WAIT 1000 //or whatever
unsigned long starttime;
starttime = millis();
while ( (Serial.available()<9) && ((millis() - starttime) < MAX_MILLIS_TO_WAIT) )
{
// hang in this loop until we either get 9 bytes of data or 1 second
// has gone by
}
if(Serial.available() < 9)
{
// the data didn't come in - handle that problem here
Serial.println("ERROR - Didn't get 9 bytes of data!");
}
else
{
for(int n=0; n<9; n++)
RFin_bytes[n] = Serial.read(); // Then: Get them.
}