Search code examples
arduinoxbee

Arduino Timing issue with Digi Xbee V1 Read function in Loop()


I am beginning to work with XBee RF Modules and have a general concern as to how and why this timing issue occurs... The two XBee do indeed communicate, and I am testing one thru Shield on Arduino Uno and the other via USB Connector on PC and X-CTU. The code is (generally) as follows, using the sample code from Sparkfun as a base (located at https://learn.sparkfun.com/tutorials/xbee-shield-hookup-guide)

// We'll use SoftwareSerial to communicate with the XBee:
#include <SoftwareSerial.h>
// XBee's DOUT (TX) is connected to pin 2 (Arduino's Software RX)
// XBee's DIN (RX) is connected to pin 3 (Arduino's Software TX)
SoftwareSerial XBee(2, 3); // RX, TX

void setup()
{
  // Set up both ports at 9600 baud. This value is most important
  // for the XBee. Make sure the baud rate matches the config
  // setting of your XBee.
  XBee.begin(9600);
  Serial.begin(9600);
}

void loop()
{
  if (XBee.available())
  { // If data comes in from XBee, send it out to serial monitor
    Xbee.write("ready");
    Serial.write(XBee.read());
  }
}

My concern comes with the fact I am sending packets of 2 ASCII chars (2 digits, 10, 20, 30, etc) just to test. In the console monitor of X-CTU, I notice the following. (bold being received, italic being sent.)

10 readyready 20 readyready 30 readyready etc...

Can someone explain to me in layman's terms of how this is occurring? I cannot understand how the code executes in this order.


Solution

  • You're using "AT mode" or "transparent serial" mode on your XBee, so characters arrive one at a time. There isn't any packetizing going on.

    So you send a packet with 10 from X-CTU. The XBee on your Arduino receives that packet and starts sending the payload to the Arduino. The Arduino receives 1 which triggers the code to send ready in response. Then the Arduino receives 0 and sends another ready.

    You would need to add some sort of framing to your serial stream (like adding a carriage return after each line of data) or switch to API mode (which delivers network payloads wrapped in headers and a checksum) if you want to look at your data in chunks, instead of as a stream.

    I haven't used it, but there's an xbee-arduino library designed for using XBee modules in API mode on Arduino microcontrollers.