0

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

void loop() {
    digitalWrite(Sleep_Rq,LOW);

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

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

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.

Serial.println(x);

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

if(x=="OK")
  {
   Serial.println(1);
  }
}

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,

if(Serial.println(x)=="OK") 
    {
     Serial.println(1);
    }

and many more techniques with no luck to be found.

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, privacy policy and cookie policy

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