How can one read an integer from serial as fast as possible?

I had a very similar problem with Serial.parseInt() taking much longer to execute than anticipated and changing the baud rate from 9600 made no discernible difference. I was sending commands to the Arduino from a Python program (to either reset an attached bn0O55 gyroscope or to send the current yaw). By replacing

command = Serial.parseInt();

with

command = Serial.read() - '0';

the time lapse between sending the command and receiving a response became negligible. This will only work if the command is a single integer between 0 and 9. The reason for the - '0' is explained nicely in this video: Tutorial 06 for Arduino: Serial Communication and Processing - YouTube at around 3:29.

Have a look at the examples in Serial Input Basics - simple reliable non-blocking ways to receive data. There is also a parse example to illustrate how to extract numbers from the received text.

...R

Try this:

void setup() {
  Serial.begin(115200); // set serial monitor line ending
                        // to new line
}
void loop() {
  // if there's any serial available, read it:
  while (Serial.available() > 0)
  {
    // look for the next valid integer in the incoming serial stream:
    int tmp = Serial.parseInt();
    // look for the newline. That's the end of your sentence:
    if (Serial.read() == '\n'){} // kills 1 second wait
    Serial.println(tmp);  
  }
}

outsider:
Try this:

Serial.parseInt() is a blocking function and will slow things down.

...R

This thread is nearly 6 years old 8). Must be a record :smiley:

sterretje:
This thread is nearly 6 years old 8). Must be a record :smiley:

It seems to have been split.

...R

I think that @cinti originally posted the reply in How can one read an integer from serial as fast as possible? - Programming Questions - Arduino Forum.