Search code examples
c++arduinoserial-portzigbeepacket-loss

Zigbee/Xbee as Receiver and Transmitter - missing packets on receiver side


I have one Arduino Uno and another Arduino Mega Board. Both have got Zigbee Shield mounted on them. One of them is working as Transmitter (Uno) and another (Mega) as a receiver.

Code for Tx:

void setup() {
    Serial.begin(9600);
}
void loop() {
    Serial.println("High"); 
    delay(200);
    Serial.println("Low");
    delay(200);
}

Code for Rx:

char msg;
const int led = 13; //led at pin 13
void setup() {
    Serial.begin(9600);//Remember that the baud must be the same on both arduinos
    pinMode(led,OUTPUT);
}
void loop() {
    while(Serial.available() ) {
        msg=Serial.read();
        if(msg=='H') {
            Serial.println("Message High");
        }
        if(msg=='L') {
            Serial.println("Message Low");
        }
        delay(200);
    }
}

On Tx side it is sending packets serially High Low

High
Low
High
Low
High
Low
High
Low
High
Low
High

However on the receiver side, I get some packets missing. It is like

Message High
Message High
Message Low
Message High
Message High
Message High
Message Low
Message Low
Message Low
Message Low
Message Low
Message Low
Message Low
Message Low
Message Low

I would expect that it should print

Message High
Message Low
Message High
Message Low

How can I receive packets synchronously and how can I be aware of any packet loss on the Rx side?


Solution

  • First off, this statement is false: "Remember that the baud must be the same on both arduinos." You can run at different baud rates on each end of the wireless link, since the XBee modules buffer your requests. The XBee baud rate just determines the line speed of the serial connection between your host and the radio module. Everything is sent "over the air" at 250kbps.

    Second, the problem is that you have a delay inside your while loop on the receiver. With that delay, you can only process one character every 200ms, so you're overflowing your buffer. The other end is sending 7 characters ("HighLow") every 400ms, and you only process 2 of them in that time.

    Move the delay outside of the loop and you should be fine.