Using C++ String objects and black box functions are a big part of where you went wrong.
The proof is that you don't know what's happening and haven't been able to figure it out.
Whereas if you use C char array strings (note the lowercase s) and read the characters one by one, your code can evaluate and react at that level with certainty.
The second link at the bottom of my post is to a blog that teaches non-blocking serial I/O.
The first link is more basic and begins to cover not making everything stop and wait for one thing.
I can't post so much so well as those blogs. They will show you a different way to look at code, a 'real time as it happens' view. If your code "can't chew gum and walk at the same time" then this is what you're missing, or at least the start.
My code works if Serial monitor is in no end line. but in "NL & CR" it does not work.
If you capture a String with a nl and a cr, then the nl and cr are also part of the String and they will effect the comparison you are making. The below simple serial test code looks for the commands in the captured String even if there are other characters in the captured String.
// zoomkat 8-6-10 serial I/O string test
// type a string in serial monitor. then send or enter
// for IDE 0019 and later
//A very simple example of sending a string of characters
//from the serial monitor, capturing the individual
//characters into a String, then evaluating the contents
//of the String to possibly perform an action (on/off board LED).
int ledPin = 13;
String readString;
void setup() {
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
Serial.println("serial on/off test 0021"); // so I can keep track
}
void loop() {
while (Serial.available()) {
delay(3);
char c = Serial.read();
readString += c;
}
if (readString.length() >0) {
Serial.println(readString);
if(readString.indexOf("on") >=0)
{
digitalWrite(ledPin, HIGH);
}
if(readString.indexOf("off") >=0)
{
digitalWrite(ledPin, LOW);
}
readString="";
}
}