I am working with an XBee module, so naturally, I started my void loop with AT command testing.

void loop() {

A +++ with a guard time of 1 sec before and after it, sets xbee module in command mode.

xbeeSerial.write("+++");              // Enter Command Mode

This part of the code, puts the serial data into string variable x in the form of a String.

while(xbeeSerial.available()) {              
    x = xbeeSerial.readString();           

Serial.println() is returning OK onto the serial monitor.


But when I compare x with OK nothing happens, 1 doesn't appear on the serial monitor.


I tried swapping "OK" with 4F4B (ascii equivalent of OK), 20299 (decimal value). I also tried changing datatype of x from String to word and compared x with 0100111101001011. I also tried changing the IF condition as,


and many more techniques with no luck to be found.

  • X is probably not "OK" but "OK\n" or "OK\r" or even "OK\r\n". Read: majenko.co.uk/blog/reading-serial-arduino
    – Majenko
    Commented Mar 6, 2019 at 12:19
  • @Majenko, you should post that as an answer so the OP can accept it and everybody can tell that the question has been answered.
    – Duncan C
    Commented Mar 6, 2019 at 13:38
  • @DuncanC I don't know which of those is the actual fix... Also I'm busy...
    – Majenko
    Commented Mar 6, 2019 at 13:42
  • Oh, sorry, I didn't mention. The correct one is "OK\r". Commented Mar 6, 2019 at 14:03
  • 2
    Possible duplicate of String compare when using Serial
    – Juraj
    Commented Mar 6, 2019 at 14:45

1 Answer 1


Your problem is that you are assuming that all you see in the Serial Monitor is all there is. You see "OK", so you expect to compare the text that comes in with "OK".

However it's not. Serial communication (at least, text based serial communication) generally includes some kind of line ending marker. That could be any combination of Carriage Return (\r) and/or Line Feed (\n). Different devices use different combinations.

As it turns out the XBee uses '\r' as the line ending marker.

There are two ways of dealing with it:

  1. Include the line ending in your comparison ("OK\r"), or better,
  2. Incorporate the line ending in the reading.

The second point there involves the use of readStringUntil():

String x = xbeeSerial.readStringUntil('\r');

That is a more reliable way of reading the response since it reads everything up to the line ending, rather than reading until it times out with nothing else to read. You should find your whole program runs smoother with that method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.