1

I want to print error in case the word that i entered in the serial monitor is different from 9 of lenght but it prints error all the time because the program itself doenst know when i´m entering a word.

// C++ code
//
void setup()
{
 Serial.begin(9600);
 Serial.println("Checksum");
}

void loop()
{

  String s = Serial.readString();

  if (s.length() == 9)
  {
    for (int i = 0; i < 9; i++)
    {
      Serial.print(s[i]);
      Serial.println(" ");
      Serial.print((byte)s[i], HEX);
      Serial.println(" ");
      Serial.println(" ");
      Serial.println();
    }


    Serial.println("Ok");
  }

  if (s.length() != 9)  
   {
    //Serial.println("Error"); //here is the error
   }

}
Matt
  • 11
  • 3

1 Answers1

0

You only want handle the input if the user entered something. To test if there are some incoming characters, test Serial.available() before Serial.readString().

readString waits for the next character until timeout. Default timeout is 1000 milliseconds. So if you send a string from Serial Monitor, the readString function will wait one second after the last received character. You want to set a shorter timeout since the time between the received characters is in microseconds range. For example use Serial.setTimeout(10); to set the timeout to 10 milliseconds.

As an alternative to readString you can use readStringUntil or if you want to read into a characters buffer, then readBytesUntil.

If you have in Serial Monitor the line endings setting set to something else than 'no new line characters", then the received String will end with one or two new line characters which will make it longer then you expect. To remove these white space characters and any spaces around the entered text, you van use trim function of String as s.trim();

Juraj
  • 3,490
  • 4
  • 18
  • 25