As part of my porting of my devices to the latest version of the Arduino IDE, I decided to move the devices to using the XBee library. Back in part 1 I described why I suddenly took an interest to it, and since I was going into the code, I might as well start using it for real at the same time. The changes to make my XBees receive packets using the library went without a hitch. It just worked fine and reduced the code I had to write by a lot. However, when I looked at transmitting data, I was appalled. All the examples show something like:
I mean REALLY?? Setting the bytes into an array one at a time? Well, I went searching the web to see what else could be done and found dozens of examples of this kind of thing. Here's one from the New SoftSerial example:
Yes, that's all there is to it; this example will compile and run using IDE 1.0.3 on a Mega2560. Andrew made the library quite capable, but most people don't seem to want to look deeply enough into it to use it to advantage. Notice that you fill in the Tx request with an address and then send the string pointer and its length to the XBee. It's just that simple. You can use a buffer and format it to be exactly what you want, then hand it off to the xbee.send() for transmission. Really, really nice.
Remember though this example is for a mega2560 with four serial ports. To do exactly the same thing on a UNO, just use SoftwareSerial as I described in part 1. It will work equally well and you still have the Serial to output status and debugging information so you can see what is going on.
Suppose you want to send the packet to a specific XBee on your network, avoiding the problems that can happen with broadcast <link> it's actually really easy. Just create another address like the one for Broadcast in the example above and use it instead.
Using this technique, I reduced a fifty or so line transmit routine down to:
Yes, I can compose the commands for my various devices and then just call sendXbee() with the string. Simple, easy to read, and it works.
I like my little XBees more and more each day.