I am having a very weird problem when reading serial data sent from my computer via USB. Here’s the code
void setup()
{
Serial.begin(9600);
}
void loop()
{
char fbuff;
char sbuff;
int first=0;
int second=0;
if (Serial.available())
{
delay(5);
fbuff=Serial.read();
sbuff=Serial.read();
first=atoi(&fbuff);
second=atoi(&sbuff);
Serial.println(first);
Serial.println(second);
}
}
This is just a prototyping code so I know i will only be receiving 2 numbers from the serial. The problem is when I read it “first” ends up printing both numbers but if I take Serial.println(second); out it reads and prints just fine. What am I doing wrong? In fact I took the second print out and added an if statement to check both of them and it messes up again. again ideas or suggestions.
Ok I figured a way around the problem. Still don’t know why it happened but here is what i changed it to for future reference.
if (Serial.available())
{
buffer=Serial.read();
first=atoi(&buffer);
delay(5);
buffer=Serial.read();
second=atoi(&buffer);
Serial.println(first);
Serial.println(second);
}
rocketboy07:
Ok I figured a way around the problem. Still don’t know why it happened but here is what i changed it to for future reference.
Here’s my guess at what happens. The IF loop, while waiting for a serial byte to come in, is tight and but as soon as one byte comes in you wait another 5 msecs. That’s more than long enough for the 2’nd byte to come in (so long as they were transmitted nearly back to back). Because the 1’st variable is an int you end up with both bytes in that variable. The 2’nd variable is then a re-read of the last byte transmitted (though this seems odd to me). If interested you could use the available() query in your original code after the 5 msec delay and see what it returns, a 1 or a 2. Then after your original 2’nd read do another/3’rd read and see if it also comes back with the last/2’nd byte. I guess you could also do this latter part in your revised code and see the same result. It might be worth knowing if the last byte stays in the UART register until it’s either flushed or a new byte comes in.
The revised code works because there’s no time for the 2’nd byte to come in before the 1’st read is done and so you only store that 1’st byte.