1

with the following sketch I should be able to read and store what is entered in the Serial monitor

void setup() {
  Serial.begin(115200);
  while(!Serial);
}

void loop() {

  Serial.println("Enter Zone Number: ");
  while(!Serial.available()){
  }
   int zone = Serial.parseInt();
   Serial.println(zone);

}

if I enter "1" I would except this:

Enter Zone Number: 
1

but unfortunately I have this:

Enter Zone Number: 
1
Enter Zone Number: 
0

What am I missing?

3

.parseInt() reads incoming text up until either it times out or until it reads something that isn't a number.

You are sending a number, and most likely a line-ending. If that line-ending is a simple \n then that will trigger the "end of number" and will be discarded and the number returned. However, if you are sending \r\n (i.e., CRLF) then you effectively have two line endings there:

1\r\n

Parsed as:

1\r => return 1
\n => return 0

Relying on the (poorly written) Arduino stream parsing routines is not good. Not only are they blocking, but often they just don't work right.

Instead you should be reading the serial properly, taking account of line endings, and then converting the string you have read into a number using the likes of atoi().

Tutorial on reading serial:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.