String comparison not working

I want to be able to send a "ping" through the serial monitor and receive a "pong" back. Everything in the function works as intended except for the ping pong part

void serialEvent()
{
  String data = Serial.readString();
  if (data == "ping") {
    Serial.println("pong");
  }
  else {
    red = data.substring(data.indexOf("r") + 1, data.indexOf("g")).toInt();
    green = data.substring(data.indexOf("g") + 1, data.indexOf("b")).toInt();
    blue = data.substring(data.indexOf("b") + 1).toInt();
    setColor(red, green, blue);
  }
}

Try setting line endings in serial monitor to No line ending. With line set otherwise extra characters are sent (carriage return ['\r'] and/or line feed ['\n'])'. "Ping" is not the same as "Ping\r\n" or "Ping\n".

Are you aware of the potential memory problems that are possible by using the String class. See the Evils of Strings page for more information.

The serial input basics tutorial shows how to read serial data without using the String class and blocking functions like readString().

1 Like