0

I want it to be where if the string contains a certain character it would do one thing. For example if Serial.readString(); reads X100Y100 then I want to check if it contains an X or not. What I have so far is:

void serialEvent() {
    serialData = Serial.readString();
    if (serialData.indexOf('X')) {
        serX.write(parseDataX(serialData));
    } else {
    // Doesnt contain the character X
    }
}

Would this work?

Jack W
  • 15
  • 1
  • 10

1 Answers1

3

If X is found, indexOf() will return its index. If it is found at index 0, your if statement will evaluate to false. Likewise, if X is not found, indexOf() will return -1, which your if statement will evaluate as true. To check if X exists in serialData, you need to check if indexOf() does not return -1:

if (serialData.indexOf('X') != -1)

See the indexOf() documentation for more information.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
cischa
  • 414
  • 2
  • 8