Get the number of bytes (characters) available for reading from the serial port. This is data that's already arrived and stored in the serial receive buffer (which holds 64 bytes).
I'm sending 5 bytes but I get the number 1 four times, then the number 2 once, and then the number 1 once again (I guess the Carriage Return and the New Line characters are there too). Shouldn't the serial receive buffer get 5 bytes (or 7 with the CR and NL)?
What I want to do is get notified of when the buffer is emptied, but this way, if I include an 'else' after ' if (Serial.available())', I get alternating 1s and 0s for every character of the string sent to the Arduino.
Can someone explain why Serial.available() returns these values and the buffer is never filled with all the bytes of the string sent?
The serial connection is really slow compared to the Arduino's processor.
What happens is: One byte arrives, Serial.available == 1, you read the byte, it is removed from the buffer, so Serial.available == 0, then the Arduino just keeps repeating the loop, checking Serial.available, until you receive the next byte, Serial.available == 1, you read it, Serial.available == 0, etc ...
If the code that handles the read byte (your if/else statements etc.) takes a long time to complete, it is possible that you receive more than one byte while this code is running. So when the code finally finishes, and you repeat the loop again, it checks Serial.available, and it will be more than one.
Receiving bytes into the RX buffer happens in the background, independent of what the CPU is doing.