Hardware Reference
In-Depth Information
while (softSerial.available()){
softSerial.read(); // on error flush software serial buffer
}
}
}// end looking for start byte
}// end loop
Part 2 of the program contains the functions to calculate the checksum and parse the packets' data. The
calcChecksum function pulls the length of the packet from the first two bytes after the packet start, and then the
checksum is calculated before retuning back to the loop function. When the processPacket function is called, the
user is informed that the packet has the correct checksum; the code then determines the packet type using the fourth
position of the packet. The switch statement responds to a transmission-reply packet ( 0x8B ) and a data-receive
packet ( 0x90 ). The transmission-reply packet is handled by informing the user by printing to the serial monitor. The
data packet is handled by parsing out the address of the sending XBee and pulling out the data to be used to construct
a reply packet. During the whole process, the information is printed to the serial monitor.
Listing 5-1. Arduino Packet Echo Code, Part 2 of 3
void calcChecksum () {
calcsum =0; // begin calculating errorsum of incoming packet
length = incomePacket[1] +incomePacket[2];
for (int i = 3 ; i <= length+2 ; i++){
calcsum = calcsum + incomePacket[i];
}
calcsum = 0xFF - calcsum; // finish calculating errorsum
} // end void calcChecksum ()
void processPacket(){
Serial.println ("Packet has correct checksum ");
switch (incomePacket[3]){ // check packet type and perform any responses
case 0x90:
Serial.println ("The packet is a data packet"); // announce packet type
for (int i = 4 ; i <= 13 ; i++){ // get both addresses of the source device
sourceADR[i-4]= incomePacket[i];
}
datalen = count - 16 ; // reduce to just the data length to get the data
for (int i = 15 ; i < datalen+15 ; i++){
incomeData [i-15] = incomePacket[i]; // phrase out the data
}
Serial.print ("source addess is: "); // begin printing 64 bit address
for (int i =0 ; i < 7 ; i++){
Serial.print (sourceADR[i],HEX);
Serial.print (' ');
}
Serial.println (sourceADR[7],HEX); // finish 64-bit address
Serial.print ("network addess is: "); // begin printing 16-bit address
Serial.print(sourceADR[8] ,HEX);
Serial.print (' ');
Serial.println(sourceADR[9] ,HEX); // finish 64-bit address
Serial.print ("the packet contains: "); // start printing the data from packet
for (int i =0 ; i < datalen ; i++){
Serial.print (incomeData [i]);
 
Search WWH ::




Custom Search