Hardware Reference
In-Depth Information
Both require you to change the X-CTU COM setting back to 9600 to accommodate the new setting. This example
is one-sided, so packets sent to the Arduino will still have to be constructed in the terminal of the X-CTU; the HELLO
packet will work for this example, although any properly formed transmit request will work with this code. To finish
the setup for this example, step through the code and upload it to the Arduino.
Listing 5-1 is comprised of three parts. The first part sets up the variables and all the initialization of the Arduino's
serial connections before entering the loop function. The loop functions waits for the software serial to be available and
checks for the packet start byte of 0x7E . A loop captures the packet and counts the incoming bytes while the software
serial is available. When the packet is received, the user is informed of the incoming packet along with the contents of the
raw packet by printing the details to the serial monitor before processing the packet. The first part of packet processing
is to calculate the checksum by calling a function. If the checksum is correct, the program continues with parsing the
packet and constructing and sending a reply packet that contains the same data that the received packet contained.
Listing 5-1. Arduino Packet Echo Code, Part 1 of 3
#include <SoftwareSerial.h>
byte incomePacket[80]; // buffer for incoming data
char incomeData [64]; // phrased data holder
byte replyPacket[80]; // packet construction buffer
byte sourceADR[10]; // source addresses
int datalen; // length of data received
int count; // total length of incoming packet
int length; // misc. length holder
byte calcsum ; // checksum
SoftwareSerial softSerial(2, 3); // the main software serial
void setup() {
Serial.begin(57600); // serial to monitor
softSerial.begin(9600); // serial to XBee
Serial.println("Ready");
} // end setup
void loop(){
if (softSerial.available() && 0x7E == softSerial.read() ){ // check for start byte
incomePacket[0] = 0x7E;
count = 1;
while (softSerial.available()){
incomePacket[count] = softSerial.read(); // receive the incoming packet
count ++; // keep track of incoming bytes
} // end while (softSerial.available())
Serial.println ("Recived a new packet");
Serial.print ("Incoming packet is: ");
for (int i = 0 ; i < count-1 ; i++){ // print raw packet
Serial.print (incomePacket[i],HEX);
Serial.print (' ');
}
Serial.println (incomePacket[count-1],HEX); // last byte of the raw packet
calcChecksum ();
if (calcsum == incomePacket[count-1]){ // throw error if the checksum does not match
processPacket();
} // end if calcsum
else {
Serial.println ("Error packet is not proper"); // the error when packets are malformed
 
Search WWH ::




Custom Search