Learn how to use HardwareSerial to communicate to an XBee device across the TX/RX pins.
This sample requires the XBee to run in API mode, by setting AP=2. If you are using Series 2 XBee, you’ll need to install the API Firmware with X-CTU (Series 2 are manufactured with AT firmware), then set AP=2. This software will not work correctly with AP=1
If you have an XBee Adapter, connect the wires to the equivalent pin-outs on the adapter.
#include "stdafx.h"
#include "arduino.h"
int _tmain(int argc, _TCHAR* argv[])
{
return RunArduinoSketch();
}
/**
Writes a message to the XBee device using the API protocol (AP=2).
@param[in] messageType The XBee API Message type
@param[in] frameId An ID for the message frame to associate with the response. Set to 0x00 if no response is required
@param[in] frame A byte array with the payload of the message
@param[in] frameLen The length of the frame array
*/
void writeXBeeApiMessage(uint8_t messageType, uint8_t frameId, uint8_t* frame, USHORT frameLen)
{
int sentLen = Serial.write((uint8_t) 0x7E); //Write header
//Write message length
USHORT len = frameLen + 2;
sentLen += Serial.write((uint8_t) (len >> 8));
sentLen += Serial.write((uint8_t) (len & 0xFF));
sentLen += Serial.write(messageType); //write message type
byte checksum = 0xFF - messageType;
sentLen += Serial.write(frameId); //write frame id
checksum -= frameId;
for (int i = 0; i < frameLen; i++) //write body
{
sentLen += Serial.write(frame[i]);
checksum -= frame[i];
}
sentLen += Serial.write(checksum); //write checksum
if (sentLen == frameLen + 6)
Log(L"Sent %d bytes\n", sentLen);
else
Log(L"Error writing bytes");
}
void setup()
{
Serial.begin(CBR_9600, Serial.SERIAL_8N1);
//Send the AT Request (0x08) for the device's ID (0x49, 0x44)
uint8_t idRequest[8] = { 0x49, 0x44 };
writeXBeeApiMessage(0x08, 0x01, idRequest, 2);
}
// This method will be called when data is available on the Serial port at the end of the loop
void serialEvent()
{
int available = Serial.available();
if (available)
{
Log("Received %d bytes: ", available);
for (int i = 0; i < available; i++)
{
auto byte = (uint8_t) Serial.read();
Log("%.2X,", byte);
}
Log("\n");
}
}
void loop()
{
Sleep(250);
}