Serial.available() timing

I'm receiving numbers over Bluetooth, via a HC05 from an Android app, using Serial.read().
It looks like it could be useful for me record the number of bytes available in the serial input buffer, so I've tried using ...

if Serial.available() >0
{
  int rxCount = Serial.available();
  // stuff
}

But knowing that serial comms is relatively slow, it seems that that rxCount gets updated before anything other than the 1st byte arrives in the serial input buffer, and rxCount is only ever 1, no matter how long the incoming data .
So I've added a delay ...

if Serial.available() >0
{
  delay(1000);
  int rxCount = Serial.available();
  // stuff
}

... which now correctly records the number of incoming bytes.
I've no doubt a second is completely excessive, but what is a pragmatic delay to use here?

none... you should not try to second guess the timing of an asynchronous protocol...

I would suggest to study Serial Input Basics to understand the usual approach to this

No delay().
If you want a sketch to be responsive and working smooth, then try to avoid all delays.
The usual way is to read a byte as soon as it is available and put it in a buffer.

const int bufsize = 40;
char buffer[bufsize];

void loop()
{
  if(Serial.available() > 0)
  {
    buffer[index] = Serial.read();
    index++;
    if(index >= bufsize)
      index = bufsize - 1;
  }
}

My bad. My function is already based on one of the Serial Input Basics examples. I'd just failed to connect the fact that there was an array index recording what I needed with what I wanted to do. Doh!

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.