Why does entering serial data lag my code

This is a test program. I am trying to read from serial, and it works, but it lags for a full second before continuing.

String test;

void setup() {
  Serial.begin(115200);
}

void loop() {

  if(Serial.available() > 0){
    test = Serial.readString();
    Serial.println("New data!");
  }
  Serial.print("message is: ");Serial.println(test);
}


image backup link
On the timestamps, you can see it takes nearly a full second for the program to give a return when I enter "hello" into the serial monitor. Is there any way I can fix this? For my project I can't have this lag.

Look at the doc for readString() and notice how it knows when to return (timeout is 1s by default )

Please don’t post pictures of text … just copy the text and post using code tags

test = Serial.readString();

This function reads the Serial input then waits for 1 second to ensure that all characters have been read before returning. You can change the timeout period.

See https://docs.arduino.cc/language-reference/en/functions/communication/Serial/readString/

This can be a nice read: Serial Input Basics - updated

1 Like

use readStringUntil()

String test;

void setup() {
    Serial.begin(115200);
}


void loop() {

    if(Serial.available() > 0){
        test = Serial.readStringUntil('\n');
        Serial.println("New data!");
    }
    Serial.print("message is: ");
    Serial.println(test);
}