Compare Strings - whats wrong?

Hi folks,

i tried to play around with the Serial communication example sketch ( http://www.arduino.cc/en/Tutorial/SerialEvent ), i want the atmel to respond with the uptime (millis()) when the inputString == "uptime"

I tried some methods of comparing i found, but none of the five seem to work.

   //if (String(inputString) == String("uptime"))
   if (inputString == "uptime")
   //if(inputString.equalsIgnoreCase("uptime"))
   //if (inputString == String("uptime"))
   //if(inputString.equalsIgnoreCase(String("uptime")))
   {
       Serial.println("uptime=");
       Serial.println(millis());
   }

The rest of the code follows the Example-> 4. Communication -> SerialEvent

Regardless which if statement i use, the two serial.println are not executed :-/
I didn't find any other posts with similar problems, but there must be an obvious one i dont see :wink:

thanks for your help!

The rest of the code follows the Example-> 4. Communication -> SerialEvent

If you want help, you'll post your code. "follows the example" != is

I think the problem is that String inputString contains the terminating '\n' character.

It might be sufficient to compare to "uptime\n":

if (inputString == "uptime\n")

A better solution might be to re-write serialEvent():

void serialEvent() {
  while (Serial.available()) {
    // get the new byte:
    char inChar = (char)Serial.read(); 
     // if the incoming character is a newline, set a flag
    // so the main loop can do something about it:
    if (inChar == '\n' || inChar == '\r') {
      stringComplete = true;
    } else {
   // add it to the inputString:
    inputString += inChar;
    }
  }
}

johnwasser:
I think the problem is that String inputString contains the terminating '\n' character.

THANKS! that was the hint i needed. I totally overlooked this.

I changed serialEvent to

void serialEvent() {
  while (Serial.available()) {
    // get the new byte:
    char inChar = (char)Serial.read(); 
    // add it to the inputString:
    
    // if the incoming character is a newline, set a flag
    // so the main loop can do something about it:
    if (inChar == '\n') {
      stringComplete = true;
    } 
    else
    {
      inputString += inChar;
    }
    
  }
}

And then found out that the serial Monitor also sends NL + CR, after i set this to "NL only", it works :slight_smile:

Thanks again!

seb-:
And then found out that the serial Monitor also sends NL + CR, after i set this to "NL only", it works :slight_smile:

That's why I checked for \n and/or \r.