Serial.available() false positives

I'm trying to send an int to the arduino. I've tracked the problem (I think) to Serial.available(). It seems that it stays nonzero for too long

Here's my code: int incoming;

void setup() { Serial.begin(115200); // opens serial port, sets data rate Serial.setTimeout(2); while (!Serial); // wait for serial port to connect. }

void loop() { if (Serial.available() > 0) { incoming = Serial.parseInt(); Serial.print("Incoming "); Serial.println(incoming); Serial.println("End of if statement"); delay(1000); } Serial.println("End of loop"); delay(1000); }

Here's the output from the serial monitor after I entered 1, pressed enter, then then merely allowed it to run for a while. Serial.available doesn't change to zero at the termination of the loop, but stays nonzero for one subsequent iteration every time.

End of loop Incoming 1 End of if statement End of loop Incoming 0 End of if statement End of loop End of loop End of loop

Changing the timeout time hasn't fixed it so far. And neither has anything else. Thanks for your help

Please edit your post, select the code, and put it between [code][/code] tags.

You can do that by hitting the “Code” icon above the posting area. It is the first icon, with the symbol: </>

parseInt() returns the first valid (long) integer number from the current position. Initial characters that are not integers (or the minus sign) are skipped. parseInt() is terminated by the first character that is not a digit.

In all probability you are sending a number followed by a newline or carriage-return + newline (you can configure this in the terminal monitor). It is the trailing newline you are probably seeing as a spurious character. I wouldn't use parseInt personally.

You may find something useful in serial input basics


Try using ) to see what you are really getting.

I concur with the advice that your serial data includes one or more line end characters, which is why Serial.available() is true.

functions like parseInt( ) are not useful, they cause more problems than they solve.

simple code that might be used to identify if non printable characters are being sent.

//zoomkat serial echo test 7-31-2011

char c; // incoming serial data

void setup() {
  Serial.begin(9600);  // set serial port at desired value
  Serial.println("serial echo test 0021"); // echo test

void loop() {

  if (Serial.available() > 0) { // check for serial buffer input
    c =; // read the incoming byte:

    Serial.println(c); // print the input
    //select an output format
    Serial.println(c, DEC);  // print as an ASCII-encoded decimal
    Serial.println(c, HEX);  // print as an ASCII-encoded hexadecimal
    Serial.println(c, OCT);  // print as an ASCII-encoded octal
    Serial.println(c, BIN);  // print as an ASCII-encoded binary
    //Serial.println(); // print new line for better reading