Serial.parseInt() set '0' error

I was trying to read integers from serial monitor (USING:- Serial.parseInt()), it does the expected task but then it always sets the stored value (myNumber) always to0. What's wrong with this? Please rectify the error caused by the internal functionality or programming error.

int myNumber;
String msg="PLEASE ENTER YOUR NUMBER:- ", msg2="YOUR NUMBER IS:- ";

void setup()
{
  Serial.begin(9600);
}

void loop()
{
  Serial.println(msg);
  while(Serial.available()==0)
  {

  }

  myNumber = Serial.parseInt();
  Serial.print(msg2);
  Serial.println(myNumber);
}

What is the line-ending setting in the serial monitor?

We don't use "Serial.parseInt()" and this is one of many reasons that we don't use it.

Do you know what you are sending via the Serial Monitor ?
You could be sending "123" followed by a CarriageReturn and LineFeed. You could be sending "123" without CarriageReturn and LineFeed and rely on a timeout.

To read the Serial data, it is best to check for the CarriageReturn '\r' and the LineFeed '\n' and also have a timeout.

I can fix your sketch, even though I don't like the "Serial.parseInt()":

int myNumber;
char msg[]  = "Please enter your number: ";
char msg2[] = "Your number is: ";

void setup()
{
  Serial.begin(9600);
  Serial.println(msg);
}

void loop()
{
  if(Serial.available() > 0)
  {
    myNumber = Serial.parseInt();
    Serial.print(msg2);
    Serial.println(myNumber);
    
    // Remove any trailing CarriageReturn and LineFeed
    while(Serial.available() > 0)
      Serial.read();

    delay(500);
    Serial.println(msg);
  }
}

The line ending setting is the serial monitor is "New Line".

...and that's the problem.

The "Serial.parseInt()" reads the number but not the LineFeed (or call it "New Line"). The next time the loop() runs, the "Serial.parseInt()" read that LineFeed. Then it converts the LineFeed to a number, but it can't, so it returns number 0.

We don't have that problem, because we don't use "Serial.parseInt()" :wink:

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.