Why I keep getting 0; When I enter no input
int num;
String msg = "Number Input: ";
void setup(){
Serial.begin(9600);
}
void loop(){
Serial.println(msg);
while (Serial.available() == 0){}
num = Serial.parseInt();
Serial.println(num);
}
Why I keep getting 0; When I enter no input
int num;
String msg = "Number Input: ";
void setup(){
Serial.begin(9600);
}
void loop(){
Serial.println(msg);
while (Serial.available() == 0){}
num = Serial.parseInt();
Serial.println(num);
}
Your code is parsing the data you enter into the Serial monitor.
Although you may only be typing 2 followed by 'enter' on the keyboard, the Serial monitor may be terminating your messages with a newline ('\n') or a carriage return ('\r').
The problem here is that Serial.parseInt() will read whatever characters are in the Serial monitor. When there is a 2 or a 3 it works fine, but, by default, Serial.parseInt() is designed to ignore, or skip, any characters that are not 0-9.
Considering your loop function: as your Serial monitor is adding a second character to any number you enter, the loop will skip the next while(Serial.available() ==0){} as '\n' or '\r' is available in the Serial stream which is what Serial.parseInt() is then trying to read.
When parseInt() can't find a suitable integer it will time out and return a 0.
There are quite a few ways to fix this, the easiest would be the change your ending selection in the Serial monitor to 'No line ending: append nothing'.
thank you it worked changing to 'No line ending'
@code_killer008, your topic has been moved to a more suitable location on the forum.
This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.