Use Serial.parseInt() to send a integer but arduino reads a 0 after my input in Monitor

Hi everyone!
I am having problems sending an integer number through serial monitor to Arduino UNO.
What I want to do is letting arduino wait until I put a number in the Monitor, then read and use the number to do something in myFun().
I read some tutorials and tried to use Serial.parseInt(). My code:

void loop() {
  Serial.println("Enter a value smaller than 4095:"); 
  while (Serial.available()==0 ){
  }
  int Val = Serial.parseInt();
  Serial.println(Val);
  //then myFun(Val)
  }

The problem is everytime I send a number, the loop() will run two times. The second time seems like a zero is the input, which changes the values in myFun too. For example, when I enter 9 it shows in the monitor:

Blockquote
Enter a value smaller than 4095:
9
Enter a value smaller than 4095:
0
Enter a value smaller than 4095:

Can someone tell me why and how can I prevent this so I can keep the return value in myFun() before I send a new number?

Thanks in advance!

What is the line ending in serial monitor set to? If it's not 'no line ending', the Serial monitor will send one or two characters extra and that will result in the extra 0.

It's Newline

So change it :wink:

AHHH I didn't see "not" in your first reply.
Now I changed and everything works!!
Thank you :grinning:

There is a way that throws away the rest of the data that remains in the serial buffer after reading like this from paseint ().

RV mineirin

void loop() {
  Serial.println("Enter a value smaller than 4095:");
  while (Serial.available() == 0 ) {
  }

  int Val = Serial.parseInt();

  Serial.println(Val);

  while (Serial.available() > 0 ) // While have something
  {
    int trash = Serial.read();   // Cleaner buffer
    delayMicroseconds(10);
  }
  //then myFun(Val)
}

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