I'm trying to read a number from the serial port, but every time I enter a number, the Arduino reads the number and reads 0 after that. Can someone help me, please? (I'm using the Arduino Uno R3)
int myNumber;
String msg1 = "Please enter your number";
String msg2 = "Your number is ";
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
Serial.println(msg1);
while(Serial.available()==0){
}
myNumber = Serial.parseInt();
Serial.print(msg2);
Serial.println(myNumber);
delay(1000);
}[code]
Set 'line ending' to 'none' and let the .parseInt() time out (default 1 second).
Or:
Set 'line ending' to 'newline' or some other setting that adds a non-digit at the end of the string.
Choice 2 is more responsive, since you don't have to wait for the timeout, but then you have to deal with the extra character.
This method works either way:
void loop() {
// put your main code here, to run repeatedly:
while (Serial.available()) Serial.read(); // Empty the input buffer
Serial.println(msg1); // Prompt for input
while(Serial.available() < 1){} // Wait until at least one character is available
myNumber = Serial.parseInt(); // Read the number until timeout or non-digit
Serial.print(msg2);
Serial.println(myNumber);
delay(1000);
}