The following code @UKHeliBob of post #10 works well even you enter 5 or more characters (including Newline character or carriage return character) from the Serial Monitor when the comparison will be made only with three character string red.
1. You are sending r e d Newline characters from Serial Monitor. The readString() method appends null-character, A null-character is automatically added at the end. Now, the String variable red contains five characters: r e d Newline Null.
2. The following equality comparison fails for reasons explained in post #11.
if (red == "red")
3. The red.c_str() method solves the problem in the following ways:
(1) The red.c_str() method converts the glued String-style string composed of red\n\0 into C-style string like: {'r', 'e', 'd', '\n', '\0'} where individual characters could be easily accessed by index/pointer (cptr) which is provided by the following code:
char *cptr = red.c_str();
The pointer variable cptr holds the base address
of the array space that contains the characters: 'r', 'e', 'd', '\n', '\0'
as individual accessible items.
(2) The strstr() function compares characters (one-by-one) of the array pointed by cptr with the source characters of red. When the matching occurs, the process ends and the following message appears on the Serial Monitor. (The Newline character (0x0A = '\n') and Null-character (0x00 = '\0') are never compared.)
$101=152
4. Sketch using c_str() method and strstr() function:
String red; // incoming serial byte
void setup()
{
Serial.begin(9600);
while (!Serial)
{
;
}
}
void loop()
{
while (Serial.available() > 0)
{
red = Serial.readString(); //store string
//if (red == "red")
if(strstr(red.c_str(), "red") != NULL)
{
Serial.println("$101=152");
}
}
}