1

I am experimenting with the following program I found online (with slight modifications):

int x;
void setup() {
 Serial.begin(9600);
 Serial.setTimeout(1);
}
void loop() {
 while (!Serial.available());
 x = Serial.readString().toInt();
 int y = x + 1;
 Serial.print(y);
}

I am encountering an error in Serial monitor output; if I input 1, I get 21 printed. I think what's happening is that every digit in a number gets incremented by 1, and then 1 is put at the end for some reason. For example, if I input 234, my output is 3451. I think the error lies with the line x = Serial.readString().toInt();, but am unsure how to fix this. Thank you!

2
  • 1
    Why such a short timeout? – Edgar Bonet Apr 16 at 18:31
  • @EdgarBonet thank you for pointing this out! I'm not sure why the tutorial did this, but changing the timeout to 100 ms seems to fix this error! – Sony Apr 16 at 18:36
3

There's two problems here.

First, you don't enter "234", you enter "2" followed by "3" and finally "4". Your really small timeout doesn't give the digits enough time to arrive.

Second, your line ending is being received and interpreted as "not a number" which is returned as 0 by .toInt().

What you need to do is:

  1. Don't set a short timeout - you can remove that line entirely.
  2. Use .readStringUntil('\n') to read up until your line ending in one go.
3
  • This worked, thank you for explaining everything too! If I remove the timeout entirely, there is notable input lag, so I just increased timeout to 100. Is there any downside to doing this? – Sony Apr 16 at 18:41
  • 1
    Yes, you get a lag. Use the readStringUntil('\n') and the timeout is not used, so you get no lag. – Majenko Apr 16 at 18:42
  • Thanks - tried it and it works awesome. – Sony Apr 16 at 18:43

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.