4

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?

asked May 31, 2016 at 13:00

2 Answers 2

5

.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:

answered May 31, 2016 at 13:17
-1

Here is a really nice and simple solution (More robust also concerning line breaks): https://stackoverflow.com/a/20962137/2714285

int x;
String str;
void loop() {
 if (Serial.available() > 0) {
 x = Serial.parseInt();
 str = Serial.readStringUntil('\n');
 }
}
answered Feb 25, 2023 at 22:10
2
  • it is a too heavy solution to get rid of one \n Commented Feb 26, 2023 at 9:47
  • If your goal is speed I understand your point but I first tried the solution of the article of Majenko and it just didn't work on linux (the \n char was just not recognized). And it's, btw, much more heavy in terms of readability / code / docs to maintain if your work in a team Commented Feb 26, 2023 at 11:32

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.