Huge delay when processing string?

While experimenting with ways to implement a command line interpreter, I discovered that the following code (on a Mega 2560) runs amazingly slowly. I’ve seen other reports of this problem, but not seen any satisfactory closure to it.

The code simply reads a string supplied to the serial buffer, and echoes it back. But it’s taking all of 1000mS to do so!

Can anyone help please? There’s got to be a way of getting response time to well below one second per string! What’s going on? Thanks…

// Simple string comms I/O test.
// Why does it take around 1000mS to reply?!?

String command_in = "";

void setup() {
  Serial.begin(9600);     // opens serial port, sets data rate to 9600 bps
}


void loop() {

  while (Serial.available() > 0) {

    command_in = Serial.readString();

    Serial.print("The Arduino received ");
    Serial.println(command_in);
  }
}

Main reason is you don't use string's, you use String's ;)

And more precise, you use the String method stringRead() which is a blocking function. And it only stops after the timeout has passed which happens to be by default 1000ms....

So tip, drop the String's and start using string's :D Have a look at Robin2's excellent thread about Serial Input Basics

Many thanks, I'll continue in that direction :D

The speed at which it takes to receive and send n characters over the serial port is based on the baud rate. Why are you using such a low baud rate?

Probably has to do with this: https://www.arduino.cc/en/Serial/SetTimeout

Regards, Ray L.