2

Serial.parseInt() reads from the serial buffer until it sees a non-numeric character or it's timeout is reached. When I use it, I put a space after the last number to make it return faster. Can I change the timeout so if I forget the number it doesn't take as long?

asked Jun 6, 2016 at 18:54

2 Answers 2

3

You can, just call

Serial.setTimeout(millisecondValue);

https://www.arduino.cc/en/Serial/SetTimeout

It defaults to one second, and controls the timeouts for readBytes, readBytesUntil, parseInt and parseFloat.

answered Jun 7, 2016 at 0:00
2

Don't use Serial.parseInt(). It is very very wrong. The whole idea behind how it operates is completely wrong and teaches bad practices and methods.

Part of your way of speeding it up is half-way to doing it properly.

You require a delimiter to say "this is the end of the number". Relying on time in a system that is inherently asynchronous is just plain daft. You have chosen to add a space. A better choice is to use a proper line ending "\n".

Then you should either read the serial character-by-character and parse it as it arrives until you find the EOL character, or read it character by character into a string (NOT a String, a "string" - a C string - a character array terminated by a NULL character), and then use atoi() etc to convert it to the numerical format you want.

Many of the methods that Arduino provide are not suitable for professional use and should be avoided at all cost lest they teach you the completely wrong way of doing things.

answered Jun 6, 2016 at 18:59
6
  • Isn't that just what the Serial.parseInt() function does minus the timeout? Commented Jun 6, 2016 at 19:05
  • It does one of those methods, yes, plus the timeout. It's the timeout that is evil, and the fact that you have no control over what happens. Better to read the data manually so you a) know what is happening, and b) have control over the entire situation. I have never, and will never, use things like .parseInt(). Commented Jun 6, 2016 at 19:07
  • Fair enough. What if EOL get garbled in transmission somehow? You wait forever? Commented Jun 6, 2016 at 19:17
  • 2
    You wait for the next EOL. But then, if you write your code properly, you won't be "waiting", you'll be "expecting". Written properly serial reading code is non-blocking and your sketch can continue doing other things until the serial data has arrived. Commented Jun 6, 2016 at 19:18
  • Good point. I will try that. Commented Jun 6, 2016 at 20:50

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.