Simple if-statement doesn't trigger - going crazy

Hi,

for one of my projects i need to read from Serial. So for example if X is received via serialEvent it should do something.

So used this example code:

And put a if-statement in there. But it never triggers. Here the code:

String inputString = "";         // a String to hold incoming data
bool stringComplete = false;  // whether the string is complete

void setup() {
  // initialize serial:
  Serial.begin(9600);
  // reserve 200 bytes for the inputString:
  inputString.reserve(200);
}

void loop() {
  // print the string when a newline arrives:
  if (stringComplete) {
    Serial.println(inputString);
    // clear the string:

    if (inputString == "x") {
      Serial.print("You typed a x");
    }
    inputString = "";
    stringComplete = false;
  }
}

/*
  SerialEvent occurs whenever a new data comes in the hardware serial RX. This
  routine is run between each time loop() runs, so using delay inside loop can
  delay response. Multiple bytes of data may be available.
*/
void serialEvent() {
  while (Serial.available()) {
    // get the new byte and check if its a new line so the main loop can do simething with it:
    char inChar = (char)Serial.read();
    if (inChar == '\n') {
      stringComplete = true;
    }
    else {
      // add it to the inputString:
      inputString += inChar;
    }
  }
}

And that's my serial output after pressing some keys (including the x) and enter afterwords:

d
x
x
x
a
d
x
f

I ask my friends who normally know better than me. And they don't know. So i hope i find a the solution here.

Thanks
ED

Try:

if (inputString == "x\r")

I could cry. Happy tears for a super quick solution and sad tears for all the time i spend :wink:

Thaaaanks a bunch

EDsteve:
I could cry. Happy tears for a super quick solution and sad tears for all the time i spend :wink:

Thaaaanks a bunch

Hope you know how it works now so I dont have to explain.

It is not a good idea to use the String (capital S) class on an Arduino as it can cause memory corruption in the small memory on an Arduino. This can happen after the program has been running perfectly for some time. Just use cstrings - char arrays terminated with '\0' (NULL).

Have a look at the examples in Serial Input Basics - simple reliable ways to receive data.

...R

EDsteve:
I could cry. Happy tears for a super quick solution and sad tears for all the time i spend :wink:

Thaaaanks a bunch

I second the comment on not using the String class and use Robin's techniques to read the input, it's better

if you do want to stick to the String approach, you could:

  • ensure your serial monitor is set up to not send additional hidden characters that would end up in your string
  • mitigate and say you want to only test if the String starts with an 'x" --> there is the startsWith() method for that

Don't be sad about spending hours on trying to debug this, that's how we learn a lesson and never do it again :slight_smile: