This may be a basic question so please bear with me.
I'm running the following code below to better understand how the Arduino serial buffer works. The code is supposed to read a serial input string, character by character into a string variable, then serial.print that same string back to me.
String str;
int count=0 ;
char charBuffer;
void setup() {
Serial.begin(9600);
}
void loop() {
while (Serial.available()!= 0) {
Serial.println("starting new while loop...");
charBuffer = Serial.read();
str += charBuffer;
count+=1;
}
if (str != "") {Serial.println(str);str="";}
}
When I try to enter text into serial monitor (in this case "Arduino"), i get a weird result:
starting new while loop...
A
starting new while loop...
r
starting new while loop...
starting new while loop...
starting new while loop...
starting new while loop...
starting new while loop...
starting new while loop...
duino
I have 2 questions:
How does Serial.read() interact with the serial buffer? My assumption is that it reads the first byte then discards it, which is how i implemented it in my code.
Why is my code escaping the while loop, even with the condition while (Serial.available()!= 0) and the serial buffer not being exhausted yet?
Delta_G's answer is of course correct. To help you further understand the Problem:
You issued a Serial.begin(9600); command to initiate Serial communications at 9600 Baud (bits per second). A single Byte of data, such as "A" is 8 bits. Serial communication also has additional bits in the protocol (parity - but the Arduino is by Default NONE) and stop bits which add a "dead space" at the end of each Byte (by Default the Arduino uses 1). There is also a start bit. So... for a single character to be transmitted it will take
(8 + 1 +1 + 0) / 9600 =0.001041667 seconds - or just over a millisecond for each character to transmit. For a microcontroller running at 16MHz, a millisecond is a Long time...
The body of loop is expected to run very frequently, there's no point whatsoever in optimizing
the case of two serial bytes arriving spacing a few microseconds part (which is what using a while
loop is implying).
Generally loop()'s body should look like:
void loop()
{
if (condition1)
handle_condition1 () ;
if (condition2)
handle_condition2 () ;
....
}
In other words its solely there to recognize when actions need to be performed and to do them.
Coding each action in a separate function is good style, it keeps loop() clean and free from any
detail that's specific to particular actions.
Note that doing things this way means you have a self-contained function for each action that
potentially can be reused from other places, and than combining several sketches into one is
much much easier.