This is my code: (it's pretty short). Could someone please tell me why I get the second line of output where it tells me my number is zero? Since I never entered a zero?
int myNumber;
String msg="Please enter number: ";
String 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);
}
Output:
Your number is: 7
Please enter number:
Your number is: 0
Please enter number:
The reason why you get the second line of output telling you that your number is zero is because the Serial.parseInt() function returns zero when it fails to parse the input as an integer. In your case, if you enter any non-numeric character (e.g. a letter, a symbol), Serial.parseInt() will fail and return zero.
To fix this issue, you can check if the value of myNumber is zero before printing it out. If it is, you can print an error message or ask the user to enter a valid input.
if not clear, the serial monitor is appending a newline to the input which is being read after the number and treated as additional input. set the serial monitor to "no line ending" near the bottom