Arduino can't read Serial properly
I figured it out.
When you open a Serial with 9600 baud (Serial.begin(9600);
), it's reading/writing at 9600 bytes per second. That means at fastest it can get just under 10 bytes per millisecond. I don't know what the operating speed is, but it seems like the Arduino gets alerted of and reads the first byte before the second one arrives. So, you must add a delay(1)
to "wait" for another byte in the "same stream" to arrive.
String read() {
while (!Serial.available()); //wait for user input
//there is something in the buffer now
String str = "";
while (Serial.available()) {
str += (char) Serial.read();
delay(1); //wait for the next byte, if after this nothing has arrived it means the text was not part of the same stream entered by the user
}
return str;
}
You may ask, well since you're delaying how do you know if the user is just typing very fast? You can't avoid it here, since the Serial is essentially limited at a certain speed. However, the user must be typing virtually-impossibly-fast for two inputs to be confused as one.
I don't have access to the Arduino source files here, but the following line of code won't give you a full String for obvious reasons (let me know if it's not that obvious):
int inByte = Serial.read();
Also, using
Serial.write()
you'll be sending byte per byte. That's the oposite from
Serial.println()
in which you'll be sending full sentences.
I would try working with Serial.print() or println() rather then Serial.write().
You can check out the references:
http://arduino.cc/en/Serial/Write
http://arduino.cc/en/Serial/Println