Problem sending data in api mode

Hi!

Finally I could send data in api mode. For the moment just 16 bit address. I will try later using 64 bit address that is what I need.

I have a problem with data sended. I have no sensors for the moment so I use an int value (135) as data coming from the sensor. The problem is that in the example, it uses:

Pin 5 is the pin which receive the data from sensor. I set this way: pin5 = 135; (Tx arduino):

payload[0] = pin5 >> 8 & 0xff;
      payload[1] = pin5 & 0xff;

If I use Serial.write(pin5); before the first payload sentence, I get 135, but if I use it after the second payload, I get something like:


The yellow part is the second Serial.print(pin5);

On the other arduino, data received is 0. I guess it is the last 0 added.
I use to read it (Rx arduino):

if (xbee.getResponse().getApiId() == RX_16_RESPONSE) {
                xbee.getResponse().getRx16Response(rx16);
        	option = rx16.getOption();
        	data = rx16.getData(0);
          }

and Serial.print(data); to print it. Just print 0 all times.

What is the proposite of payload? What can I do to solve this issue?

My complete code is the same as arduino xbee librarie. But if you need it to check it, I will post it complete.

OK, I edit. I think I solved the question. If I change rx16.getData(0); by rx16.getData(1); I obtain the 135 on the other arduino.

What happends with 0 position? I tried sending 2 values (for both sensors) and I have to use 2 and 4 positions to read both... What happends with other 2 positions?

The yellow part is the second Serial.print(pin5);

How do you know this?

Serial.print("pin5 value: [");
Serial.print(pin5);
Serial.println("]");

would convince me.

What happends with 0 position? I tried sending 2 values (for both sensors) and I have to use 2 and 4 positions to read both... What happends with other 2 positions?

Without seeing all of your code, for both ends, I wouldn't even care to guess.

I set more messages to know how much time it takes but I put :

After the second] it writes trash… I don’t know why.

My code is:

/**
 * Copyright (c) 2009 Andrew Rapp. All rights reserved.
 *
 * This file is part of XBee-Arduino.
 *
 * XBee-Arduino is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * XBee-Arduino is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with XBee-Arduino.  If not, see <http://www.gnu.org/licenses/>.
 */
 
#include <XBee.h>
#include <SoftwareSerial.h>

/*
This example is for Series 1 XBee
Sends a TX16 or TX64 request with the value of analogRead(pin5) and checks the status response for success
Note: In my testing it took about 15 seconds for the XBee to start reporting success, so I've added a startup delay
*/

XBee xbee = XBee();

unsigned long start = millis();

// allocate two bytes for to hold a 10-bit analog reading
uint8_t payload[] = { 0, 0 , 0, 0};

// with Series 1 you can use either 16-bit or 64-bit addressing

// 16-bit addressing: Enter address of remote XBee, typically the coordinator
Tx16Request tx = Tx16Request(0x1234, payload, sizeof(payload));

// 64-bit addressing: This is the SH + SL address of remote XBee
//XBeeAddress64 addr64 = XBeeAddress64(0x0013a200, 0x4008b490);
// unless you have MY on the receiving radio set to FFFF, this will be received as a RX16 packet
//Tx64Request tx = Tx64Request(addr64, payload, sizeof(payload));

TxStatusResponse txStatus = TxStatusResponse();

int pin5 = 0;
//
int pin6 = 0;

int statusLed = 13;
int errorLed = 12;

void flashLed(int pin, int times, int wait) {
    
    for (int i = 0; i < times; i++) {
      digitalWrite(pin, HIGH);
      delay(wait);
      digitalWrite(pin, LOW);
      
      if (i + 1 < times) {
        delay(wait);
      }
    }
}

void setup() {
  pinMode(statusLed, OUTPUT);
  pinMode(errorLed, OUTPUT);
  xbee.begin(9600);
}

void loop() {
   
   // start transmitting after a startup delay.  Note: this will rollover to 0 eventually so not best way to handle
    if (millis() - start > 15000) {
      // break down 10-bit reading into two bytes and place in payload
      pin5 = 135;//analogRead(5);
      //
      pin6 = 140;
      Serial.println(pin5);
      payload[0] = pin5 >> 8 & 0xff;
      payload[1] = pin5 & 0xff;
      Serial.println(pin5);
      
      //
      payload[2] = pin6 >> 8 & 0xff;
      //
      payload[3] = pin6 & 0xff;
      
      xbee.send(tx);

      // flash TX indicator
      flashLed(statusLed, 1, 100);
    }
  
    // after sending a tx request, we expect a status response
    // wait up to 5 seconds for the status response
    if (xbee.readPacket(5000)) {
        // got a response!

        // should be a znet tx status            	
    	if (xbee.getResponse().getApiId() == TX_STATUS_RESPONSE) {
    	   xbee.getResponse().getZBTxStatusResponse(txStatus);
    		
    	   // get the delivery status, the fifth byte
           if (txStatus.getStatus() == SUCCESS) {
            	// success.  time to celebrate
             	flashLed(statusLed, 5, 500);
           } else {
            	// the remote XBee did not receive our packet. is it powered on?
             	flashLed(errorLed, 3, 500);
           }
        }      
    } else if (xbee.getResponse().isError()) {
      //nss.print("Error reading packet.  Error code: ");  
      //nss.println(xbee.getResponse().getErrorCode());
      // or flash error led
    } else {
      // local XBee did not provide a timely TX Status Response.  Radio is not configured properly or connected
      flashLed(errorLed, 2, 500);
    }
    
    delay(1000);
}

ReceiveR:

#include <XBee.h>
#include <SoftwareSerial.h>

/*
This example is for Series 1 XBee (802.15.4)
Receives either a RX16 or RX64 packet and sets a PWM value based on packet data.
Error led is flashed if an unexpected packet is received
*/

XBee xbee = XBee();
XBeeResponse response = XBeeResponse();
// create reusable response objects for responses we expect to handle 
Rx16Response rx16 = Rx16Response();
Rx64Response rx64 = Rx64Response();

int statusLed = 13;
int errorLed = 12;
int dataLed = 11;

uint8_t option = 0;
uint8_t data = 0;

void flashLed(int pin, int times, int wait) {
    
    for (int i = 0; i < times; i++) {
      digitalWrite(pin, HIGH);
      delay(wait);
      digitalWrite(pin, LOW);
      
      if (i + 1 < times) {
        delay(wait);
      }
    }
}

void setup() {
  pinMode(statusLed, OUTPUT);
  pinMode(errorLed, OUTPUT);
  pinMode(dataLed,  OUTPUT);
  Serial.begin(9600);
  
  // start serial
  xbee.begin(9600);
  
  flashLed(statusLed, 3, 50);
}

// continuously reads packets, looking for RX16 or RX64
void loop() {
    
    xbee.readPacket();
    
    if (xbee.getResponse().isAvailable()) {
      // got something
      
      if (xbee.getResponse().getApiId() == RX_16_RESPONSE || xbee.getResponse().getApiId() == RX_64_RESPONSE) {
        // got a rx packet
        
        if (xbee.getResponse().getApiId() == RX_16_RESPONSE) {
                xbee.getResponse().getRx16Response(rx16);
        	option = rx16.getOption();
        	data = rx16.getData(1);
                Serial.print("Recibimos: ");
                Serial.println(millis());
                Serial.print(data);
                Serial.print(" y ");
               	data = rx16.getData(3);
                Serial.println(data);
        } else {
                xbee.getResponse().getRx64Response(rx64);
        	option = rx64.getOption();
        	data = rx64.getData(0);
        }
        
        // TODO check option, rssi bytes    
        flashLed(statusLed, 1, 10);
        
        // set dataLed PWM to value of the first byte in the data
        flashLed(dataLed, 5,data);
        
      } else {
      	// Si no es lo que esperabamos
        flashLed(errorLed, 1, 25);    
      }
    } else if (xbee.getResponse().isError()) {
      //nss.print("Error reading packet.  Error code: ");  
      //nss.println(xbee.getResponse().getErrorCode());
      // or flash error led
    } 
}

It is not very important for me because sender will never write anything by serial. But I don’t know why it happends. I tried to put a Serial.flush() before any Serial.print() but it stills happend.

After the second] it writes trash... I don't know why.

What is "it" that writes trash? It is not the Serial.println("]"); statement.

But I don't know why it happends. I tried to put a Serial.flush() before any Serial.print() but it stills happend.

The output you showed is not generated by the code you posted, so I presume that you want it to remain a mystery.

I have no more code. I load the code I post in both arduinos. With "it" I mean the arduino Serial function.

I post all code, it is an example from xbee librarie. I just changed MY value and the lecture of a sensor for: pin5 = 135;

If I use Serial function, after send data by xbee, it shows more trash. For example, if I write: Serial.println("hello"); in the last line of loop function, I will obtain "hello" and lot of trash.

What is the proposite of payload?

Hard to say.

For example, if I write: Serial.println("hello"); in the last line of loop function, I will obtain "hello" and lot of trash.

How about actually showing your output rather than saying "a lot of trash"?

It is not very important for me because sender will never write anything by serial.

I don't understand what you mean by this, nor do I understand why you want help resolving an unimportant problem.

My first question was related to payload[0]. I don’t understand why I need 2 bits in payload but it just use the second value, staying the first one in 0. But, when I try to write something by Serial to know if the trash was added during payload, I saw that Serial function seems to add trash too. So in this way, I would need to use 2 more bytes each time I add a new sensor, but just the second one would have a value.

My end nodes will just send data by xbee. But from the coordinator, I will need to send data to a computer. I don’t want to have the same problem in this case. If I have to send just sensor values and I send sensor values and many characters more… If this happends, I would have to look for another way to send data to computer, I don’t know how… ethernet or something like that.

I showed the output. The 3 last characters before last “Acabamos: 24236” are writen lot of times if I execute the loop more than 3 or 4 times.

None of the code you have posted outputs "Acabamos". Its a mystery as to how you are getting that output...

Oh, thats true.
I add this 3 lines at the top of the loop:

Serial.flush();
  Serial.print("Empezamos: "); //Empezamos = Starting: 
   Serial.println(millis());

And this 3 lines at the end of the loop to know how much time it takes:

Serial.print("Acabamos: "); //Acabamos = Ending:
    Serial.println(millis());
    Serial.flush();

But, before I use this lines, I also get these strange characters when using Serial.println(pin5); You can see it in the first capture. Added characters are the same in both captures.

You still haven't told us which version of the IDE you are using, nor have you told us why you need to flush the serial port. What do you understand the flush() to do?

The code you posted doesn't output "pin5" either. Why don't you post the whole sketch that you are currently using that generated the output you posted.

At the moment it looks like you have the XBees using the hardware serial interface so what you are seeing in the serial monitor both your Serial.print() output and the binary XBee message that is sent to the XBee. You may also be confusing the XBee since is will also be receiving everything you output with Serial.print().

I use IDE 1.0

pin5 is not an output. It is just an int variable. I just use 2 outputs for 2 leds, 12 and 13. Pin5 and 6, should be 2 sensors but I haven’t them.

I understand flush as a function which clean serial buffer. I remember of using fflush in C. I think flush should be similar. What is the real purpose?

Xbee comunicate each other without problems. Maybe they are send data also by Serial interface, because the wrong output in Serial just appears when xbee can send data to other xbee. I mean, if I discconnect the second arduino, wrong data doens’t appear in Serial monitor.

/**
 * Copyright (c) 2009 Andrew Rapp. All rights reserved.
 *
 * This file is part of XBee-Arduino.
 *
 * XBee-Arduino is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * XBee-Arduino is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with XBee-Arduino.  If not, see <http://www.gnu.org/licenses/>.
 */
 
#include <XBee.h>
#include <SoftwareSerial.h>

/*
This example is for Series 1 XBee
Sends a TX16 or TX64 request with the value of analogRead(pin5) and checks the status response for success
Note: In my testing it took about 15 seconds for the XBee to start reporting success, so I've added a startup delay
*/

XBee xbee = XBee();

unsigned long start = millis();

// allocate two bytes for to hold a 10-bit analog reading
uint8_t payload[] = { 0, 0 , 0, 0};

// with Series 1 you can use either 16-bit or 64-bit addressing

// 16-bit addressing: Enter address of remote XBee, typically the coordinator
Tx16Request tx = Tx16Request(0x1234, payload, sizeof(payload));

// 64-bit addressing: This is the SH + SL address of remote XBee
//XBeeAddress64 addr64 = XBeeAddress64(0x0013a200, 0x4008b490);
// unless you have MY on the receiving radio set to FFFF, this will be received as a RX16 packet
//Tx64Request tx = Tx64Request(addr64, payload, sizeof(payload));

TxStatusResponse txStatus = TxStatusResponse();

int pin5 = 0;
//
int pin6 = 0;

int statusLed = 13;
int errorLed = 12;

void flashLed(int pin, int times, int wait) {
    
    for (int i = 0; i < times; i++) {
      digitalWrite(pin, HIGH);
      delay(wait);
      digitalWrite(pin, LOW);
      
      if (i + 1 < times) {
        delay(wait);
      }
    }
}

void setup() {
  pinMode(statusLed, OUTPUT);
  pinMode(errorLed, OUTPUT);
  xbee.begin(9600);
}

void loop() {
   Serial.flush();
  Serial.print("Empezamos: "); //Empezamos = Starting: 
   Serial.println(millis());
   // start transmitting after a startup delay.  Note: this will rollover to 0 eventually so not best way to handle
    if (millis() - start > 15000) {
      // break down 10-bit reading into two bytes and place in payload
      pin5 = 135;//analogRead(5);
      //
      pin6 = 140;
      payload[0] = pin5 >> 8 & 0xff;
      payload[1] = pin5 & 0xff;
      
      //
      payload[2] = pin6 >> 8 & 0xff;
      //
      payload[3] = pin6 & 0xff;
      
      xbee.send(tx);

      // flash TX indicator
      flashLed(statusLed, 1, 100);
    }
  
    // after sending a tx request, we expect a status response
    // wait up to 5 seconds for the status response
    if (xbee.readPacket(5000)) {
        // got a response!

        // should be a znet tx status            	
    	if (xbee.getResponse().getApiId() == TX_STATUS_RESPONSE) {
    	   xbee.getResponse().getZBTxStatusResponse(txStatus);
    		
    	   // get the delivery status, the fifth byte
           if (txStatus.getStatus() == SUCCESS) {
            	// success.  time to celebrate
             	flashLed(statusLed, 5, 500);
           } else {
            	// the remote XBee did not receive our packet. is it powered on?
             	flashLed(errorLed, 3, 500);
           }
        }      
    } else if (xbee.getResponse().isError()) {
      //nss.print("Error reading packet.  Error code: ");  
      //nss.println(xbee.getResponse().getErrorCode());
      // or flash error led
    } else {
      // local XBee did not provide a timely TX Status Response.  Radio is not configured properly or connected
      flashLed(errorLed, 2, 500);
    }
    
    delay(1000);
    Serial.print("Acabamos: "); //Acabamos = Ending:
    Serial.println(millis());
    Serial.flush();
}

Suriken:
pin5 is not an output. It is just an int variable. I just use 2 outputs for 2 leds, 12 and 13. Pin5 and 6, should be 2 sensors but I haven't them.

Let me try again.

In the output listing from com14 in your second post you posted an image of this output:

Empezamos: 0
Acabamos: 6500
Empezamos: 6514
Acabamos: 13017
Empezamos: 13033
Acabamos: 19533
Empezamos: 19550
pin5 value: [135]
After payload pin5 value: [135]
~           4 ...Acabomos: 24236

Can you post the sketch that created that output. I don't see anything in the code so far that generates that output, with lines like "After payload pin5 value".

Although at this point I'd say don't bother. Your XBees are working fine, the output in the Serial monitor is what you'd expect to see with your XBee connected to the hardware serial port, so everything is great - its not "wrong data".

You should check the reference section of the site for any functions you are not sure of, for example Serial.flush() - Arduino Reference.

Sorry sorry, I forget to add these lines.

/**
 * Copyright (c) 2009 Andrew Rapp. All rights reserved.
 *
 * This file is part of XBee-Arduino.
 *
 * XBee-Arduino is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * XBee-Arduino is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with XBee-Arduino.  If not, see <http://www.gnu.org/licenses/>.
 */
 
#include <XBee.h>
#include <SoftwareSerial.h>

/*
This example is for Series 1 XBee
Sends a TX16 or TX64 request with the value of analogRead(pin5) and checks the status response for success
Note: In my testing it took about 15 seconds for the XBee to start reporting success, so I've added a startup delay
*/

XBee xbee = XBee();

unsigned long start = millis();

// allocate two bytes for to hold a 10-bit analog reading
uint8_t payload[] = { 0, 0 , 0, 0};

// with Series 1 you can use either 16-bit or 64-bit addressing

// 16-bit addressing: Enter address of remote XBee, typically the coordinator
Tx16Request tx = Tx16Request(0x1234, payload, sizeof(payload));

// 64-bit addressing: This is the SH + SL address of remote XBee
//XBeeAddress64 addr64 = XBeeAddress64(0x0013a200, 0x4008b490);
// unless you have MY on the receiving radio set to FFFF, this will be received as a RX16 packet
//Tx64Request tx = Tx64Request(addr64, payload, sizeof(payload));

TxStatusResponse txStatus = TxStatusResponse();

int pin5 = 0;
//
int pin6 = 0;

int statusLed = 13;
int errorLed = 12;

void flashLed(int pin, int times, int wait) {
    
    for (int i = 0; i < times; i++) {
      digitalWrite(pin, HIGH);
      delay(wait);
      digitalWrite(pin, LOW);
      
      if (i + 1 < times) {
        delay(wait);
      }
    }
}

void setup() {
  pinMode(statusLed, OUTPUT);
  pinMode(errorLed, OUTPUT);
  xbee.begin(9600);
}

void loop() {
   Serial.flush();
  Serial.print("Empezamos: "); //Empezamos = Starting: 
   Serial.println(millis());
   // start transmitting after a startup delay.  Note: this will rollover to 0 eventually so not best way to handle
    if (millis() - start > 15000) {
      // break down 10-bit reading into two bytes and place in payload
      pin5 = 135;//analogRead(5);
      //
      pin6 = 140;
      Serial.print("pin5 value: [");
      Serial.print(pin5);
      Serial.print("]");
      payload[0] = pin5 >> 8 & 0xff;
      payload[1] = pin5 & 0xff;
      Serial.print("After payload pin5 value: [");
      Serial.print(pin5);
      Serial.print("]");
      
      //
      payload[2] = pin6 >> 8 & 0xff;
      //
      payload[3] = pin6 & 0xff;
      
      xbee.send(tx);

      // flash TX indicator
      flashLed(statusLed, 1, 100);
    }
  
    // after sending a tx request, we expect a status response
    // wait up to 5 seconds for the status response
    if (xbee.readPacket(5000)) {
        // got a response!

        // should be a znet tx status            	
    	if (xbee.getResponse().getApiId() == TX_STATUS_RESPONSE) {
    	   xbee.getResponse().getZBTxStatusResponse(txStatus);
    		
    	   // get the delivery status, the fifth byte
           if (txStatus.getStatus() == SUCCESS) {
            	// success.  time to celebrate
             	flashLed(statusLed, 5, 500);
           } else {
            	// the remote XBee did not receive our packet. is it powered on?
             	flashLed(errorLed, 3, 500);
           }
        }      
    } else if (xbee.getResponse().isError()) {
      //nss.print("Error reading packet.  Error code: ");  
      //nss.println(xbee.getResponse().getErrorCode());
      // or flash error led
    } else {
      // local XBee did not provide a timely TX Status Response.  Radio is not configured properly or connected
      flashLed(errorLed, 2, 500);
    }
    
    delay(1000);
    Serial.print("Acabamos: "); //Acabamos = Ending:
    Serial.println(millis());
    Serial.flush();
}

These lines PaulS told me to add. I delete after post the capture.

I think the problem is what you said. Xbee send data for Serial too and it makes the wrong output. I will check other way to send data to pc when using xbee, in order to avoid that problem in future. By ethernet or something like that…

Sorry for problems at posting code. I am changing code all time to check things and I have to modify each time I have to upload here.

I will check function webpage.
Thanks for your time and patient.

Hi,

I’m trying to use the xbee library to make a communication between some ZB S2B modules.

I configured them in API mode (2, with escape character), at 57600 bps, and let them to associate themselves. It seems like all is OK. But I can’t see any transmitting message between them, even when I use the library’s examples.

I modified these examples, only to print message in serial, to try watching more info. I put them below.

Could you help me, please??

#include <XBee.h>

/*
This example is for Series 2 XBee
 Sends a ZB TX request with the value of analogRead(pin5) and checks the status response for success
 */

// create the XBee object
XBee xbee = XBee();

uint8_t payload[] = { 
  0, 0 };

// SH + SL Address of receiving XBee
XBeeAddress64 addr64 = XBeeAddress64(0x0013a200, 0x408615d9);    //@MAC coordinator
ZBTxRequest zbTx = ZBTxRequest(addr64, payload, sizeof(payload));
ZBTxStatusResponse txStatus = ZBTxStatusResponse();

int pin5 = 0;

int statusLed = 13;
int errorLed = 13;

unsigned long start = millis();
//___________________________________________________________________________________________

void flashLed(int pin, int times, int wait) {

  for (int i = 0; i < times; i++) {
    digitalWrite(pin, HIGH);
    delay(wait);
    digitalWrite(pin, LOW);

    if (i + 1 < times) {
      delay(wait);
    }
  }
}
//___________________________________________________________________________________________

void setup() {
  pinMode(statusLed, OUTPUT);
  pinMode(errorLed, OUTPUT);

  Serial.begin(57600);
  Serial.println("\n\t... XBee - ZB ...\n");

  xbee.begin(57600);

  flashLed(statusLed, 1, 500);
}
//___________________________________________________________________________________________

void loop() {   
  Serial.flush();

  // break down 10-bit reading into two bytes and place in payload
  pin5 = 135;    //analogRead(5);
  Serial.print("pin5 value: [");
  Serial.print(pin5);
  Serial.println("]");
  payload[0] = pin5 >> 8 & 0xff;
  payload[1] = pin5 & 0xff;

  xbee.send(zbTx);
    Serial.println("Sending TX packets.");

  // flash TX indicator
  flashLed(statusLed, 1, 100);

  // after sending a tx request, we expect a status response
  // wait up to 5 seconds for the status response
  if (xbee.readPacket(5000)) {
    // got a response!
    Serial.println("\tHaving Response.");

    // should be a znet tx status            	
    if (xbee.getResponse().getApiId() == ZB_TX_STATUS_RESPONSE) {
      xbee.getResponse().getZBTxStatusResponse(txStatus);
      Serial.println("\t\tTX STATUS");

      // get the delivery status, the fifth byte
      if (txStatus.getDeliveryStatus() == SUCCESS) {
        // success.  time to celebrate
        flashLed(statusLed, 5, 500);
        Serial.println("\t\t\tSUCCESS");
      } 
      else {
        // the remote XBee did not receive our packet. is it powered on?
        flashLed(errorLed, 3, 500);
        Serial.println("\t\t\tERROR");
      }
    }
  } 
  else if (xbee.getResponse().isError()) {
    //nss.print("Error reading packet.  Error code: ");  
    //nss.println(xbee.getResponse().getErrorCode());
    Serial.println("\tWrong Response.\n");
  } 
  else {
    // local XBee did not provide a timely TX Status Response -- should not happen
    flashLed(errorLed, 2, 500);
    Serial.println("\tNo Response.");
  }

  Serial.flush();
  delay(5000);
}
#include <XBee.h>

/*
This example is for Series 2 XBee
 Receives a ZB RX packet and sets a PWM value based on packet data.
 Error led is flashed if an unexpected packet is received
 */

XBee xbee = XBee();
XBeeResponse response = XBeeResponse();
// create reusable response objects for responses we expect to handle 
ZBRxResponse rx = ZBRxResponse();
ModemStatusResponse msr = ModemStatusResponse();

int statusLed = 13;
int errorLed = 13;
int dataLed = 13;
//___________________________________________________________________________________________

void flashLed(int pin, int times, int wait) {

  for (int i = 0; i < times; i++) {
    digitalWrite(pin, HIGH);
    delay(wait);
    digitalWrite(pin, LOW);

    if (i + 1 < times) {
      delay(wait);
    }
  }
}
//___________________________________________________________________________________________

void setup() {
  pinMode(statusLed, OUTPUT);
  pinMode(errorLed, OUTPUT);
  pinMode(dataLed,  OUTPUT);
  
  Serial.begin(57600);
  Serial.println("\n\t... XBee - ZB ...\n");

  // start serial
  xbee.begin(57600);

  flashLed(statusLed, 1, 500);
}
//___________________________________________________________________________________________

// continuously reads packets, looking for ZB Receive or Modem Status
void loop() {

  xbee.readPacket();
  Serial.println("Checking RX packets.");

  if (xbee.getResponse().isAvailable()) {
    // got something
    Serial.println("There's some RX.");

    if (xbee.getResponse().getApiId() == ZB_RX_RESPONSE) {
      // got a zb rx packet
      Serial.println("\tThere's RX packet.");

      // now fill our zb rx class
      xbee.getResponse().getZBRxResponse(rx);

      if (rx.getOption() == ZB_PACKET_ACKNOWLEDGED) {
        // the sender got an ACK
        flashLed(statusLed, 10, 100);
        Serial.println("\t\tACK");
        Serial.print("\n\tData: ");
        Serial.println(rx.getData(0));
      } 
      else {
        // we got it (obviously) but sender didn't get an ACK
        flashLed(errorLed, 2, 200);
        Serial.println("\t\tACK ERROR");
      }
      // set dataLed PWM to value of the first byte in the data
//      analogWrite(dataLed, rx.getData(0));
    } 
    else if (xbee.getResponse().getApiId() == MODEM_STATUS_RESPONSE) {
      xbee.getResponse().getModemStatusResponse(msr);
      // the local XBee sends this response on certain events, like association/dissociation
      Serial.println("\tThere's Status Rx.");

      if (msr.getStatus() == ASSOCIATED) {
        // yay this is great.  flash led
        flashLed(statusLed, 10, 100);
        Serial.println("\t\tASSOCIATED\n");
      } 
      else if (msr.getStatus() == DISASSOCIATED) {
        // this is awful.. flash led to show our discontent
        flashLed(errorLed, 10, 100);
        Serial.println("\t\tDISASSOCIATED\n");
      } 
      else {
        // another status
        flashLed(statusLed, 5, 100);
        Serial.println("\t\tOTHER STATUS\n");
      }
    } 
    else {
      // not something we were expecting
      flashLed(errorLed, 1, 25);
      Serial.println("\tUnexpected Response\n");    
    }
  } 
  else if (xbee.getResponse().isError()) {
    //nss.print("Error reading packet.  Error code: ");  
    //nss.println(xbee.getResponse().getErrorCode());
    Serial.println("There's no RX packets.\n");
  }
  
  delay(5000);
}