Using Xbee with Arduino Yún

Categories Interaction, Open-source, Programming, Technology

Came across an issue today when upgrading a project I’m currently working on to make use of an Xbee + Arduino Yún stack instead of an Xbee + Arduino Uno stack and found that the solution wasn’t very apparent online. I thought I’d post a short writeup here. Special thanks to Bo for solving this issue.

Firstly, the Yún is amazing in that is has built-in WiFi capabilities, but this also means a few peculiarities with the serial due to the split architecture. If you are trying to use an Xbee with a shield, you will need to make a few modifications to both hardware and code in order to get it working.

Firstly, we cannot use the normal serial communication pins (0,1) and instead need to use alternative pins. I assumed I could use the SoftwareSerial library to allocate another set of pins (for example 10, 11) however for reasons I still don’t fully understand this doesn’t work either.

The solution was suggested by cmaglie in this thread to use AltSoftwareSerial (download the library here). I had not heard of AltSoftwareSerial before, it is an emulated serial comm.

What you need to do is install the above library (read here if you have never done that before) and change your code to include the new serial method. The example code below will recieve packets from another device and print them to serial:

#include <XBee.h>
#include <AltSoftSerial.h>

XBee _xbee = XBee();
AltSoftSerial altSerial;

void setup()
{
  Serial.begin(9600);
  altSerial.begin(9600);
  _xbee.begin(altSerial);
}

void loop()
{
  value="";
  processXBeePackets();  
}

void processXBeePackets()
{
   _xbee.readPacket();
   if (_xbee.getResponse().isAvailable())
   {
      _xbee.getResponse().getZBRxResponse(rx);
      //Serial.println(rx.getDataLength());
      for(int i=0;i<rx.getDataLength();i++){
         value.concat(char(rx.getData(i)));
   }

   Serial.println(value);
   }
}

Then on the hardware side, you need to modify your Xbee shield (or if not using a shield, simply reroute your pin-out). This is as simple as bending out two header pins (we’ve used spacers) so that they don’t actually come into contact with their Arduino counterparts. So, pins 2 and 3 don’t connect to Arduino and we instead use some jumpers to reroute them to 5 and 13 respectively. See the images for reference:

Xbee shield working on Arduino Yun
Rerouting pin 3 > 5 and pin 2 > 13

 

sparkfun xbee shield header pins modified for serial with Yun
The header pins for 2 and 3 need to be bent so that they don’t interface with the arduino.

You should now be able to pass your Xbee communication data on to your Arduino Yún and then pass it on to a server or computer via WiFi.