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?
2 Answers 2
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.
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.
-
Isn't that just what the
Serial.parseInt()
function does minus the timeout?Marcel– Marcel2016年06月06日 19:05:28 +00:00Commented 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().Majenko– Majenko2016年06月06日 19:07:54 +00:00Commented Jun 6, 2016 at 19:07
-
Fair enough. What if EOL get garbled in transmission somehow? You wait forever?Marcel– Marcel2016年06月06日 19:17:12 +00:00Commented Jun 6, 2016 at 19:17
-
2You 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.Majenko– Majenko2016年06月06日 19:18:37 +00:00Commented Jun 6, 2016 at 19:18
-
Good point. I will try that.Marcel– Marcel2016年06月06日 20:50:29 +00:00Commented Jun 6, 2016 at 20:50