I wasn't sure where exactly to post this, because I'm not sure if it's a bug, or if I just don't understand something about the Arduino innards; if it needs to be moved, please go ahead and do so.
I noticed, when using Serial.available() when there are multiple bytes in the buffer, Serial.available() briefly returns 0 after the first byte is read before return whatever is left in the buffer. It sometimes does this at random other points in the buffer, but after the first byte seems to be 100% reproducible at lower baudrates (eg 9600). At faster baud rates (eg 115200), there is almost always a break, but it seems to randomly appear between the 1st and 5th bytes. This behaviour is alleviated by inserting a brief delay between calls to Serial.available(); 10ms appears to be enough to fix the problem, while 5 is not.
I wrote the following test code to demonstrate the problem:
// Demonstrates strange behaviour of the Serial.available() function
// Type a string in terminal to see that a linebreak gets inserted after the first byte.
// Try a long string several times to see occasional random linebreaks at other points
// Uncomment the delay to fix the problem
boolean flag = 0;
char current;
void setup(){
// Change rate to alter the problem
Serial.begin(9600);
}
void loop(){
while(Serial.available()){
current = Serial.read();
Serial.print(current);
flag = 1;
}
if(!Serial.available() && flag){
Serial.println();
flag = 0;
}
// uncomment the following line to fix the problem; feel free to play with the delay value
//delay(10);
}
There's an easy workaround for this, of course, which is to include either a delay or some other method of limiting how often Serial.available() is called. I'm just curious why it's happening. Is this a known phenomenon?