0

I have started programming Arduino in the last month. Now I'm working with a bluetooth module. But when I send some data from the Android device to the Arduino, it stays for a very short time and after that immediately it becomes 0.

Why does it become 0? And how can I get rid of that problem?

Here is my code:

int x,y;

void setup() 
{
  Serial.begin(9600);
}
void loop() 
{
  if(Serial.available()>0)
  {
    x=Serial.parseInt();
    y=Serial.parseInt();
    Serial.print("x:");
    Serial.print(x);
    Serial.print("\n");
    Serial.print("y:");
    Serial.print(y);
    Serial.print("\n");
  }
  else
  {
    ;
  }
}

and here is the result:

enter image description here

1

Serial.parseInt() has a timeout. If something arrives on the serial, or is left over from a previous transmission and hasn't been read yet, Serial.parseInt() will start looking for a number to parse. When that fails it times out (and so does the second one immediately after it). When that timeout occurs parseInt() just returns 0.

IMHO the Arduino serial parsing routines are very poorly written and should be avoided. I have some tips on how to properly read serial here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.