Hardware Reference
In-Depth Information
}
Serial.println (" : For data"); // finish the data print
constructReply();
break; // done with the received packet
case 0x8B: //start response to the return packet from sending data
Serial.println ("Received reply ");
break;
default: // anouce unknown packet type
Serial.println ("error: packet type not known");
}// end switch
} // end processPacket()
Part 3 of the code echoes the data received from another XBee. The reply packet is built one byte at a time in
an array starting with the packet start frame, the type, and the frame ID. Portions of the packet that are a single-byte
setting are set one at a time. The parts of the packet that are from the received packet are added to the outgoing packet
via for loops (the parts added include the address to send the new packet to and a copy of the received data). When
the packet is almost complete, the packet size is calculated and added. The final calculation to be added to the packet
is for the checksum before the packet is sent, and the program continues waiting for new packets.
Listing 5-1. Arduino Packet Echo Code, Part 3 of 3
void constructReply(){
Serial.println ("Constructing a reply packet"); // announce packet construction
// start adding data to the reply packet buffer
replyPacket[0] = 0x7E; // start byte
replyPacket[1] = 0; // 1st address byte will be zero with current limitations
replyPacket[3] = 0x10; // frame type
replyPacket[4] = 1; // frame ID
for (int i =5 ; i <= 14 ; i++){ // add addresses
replyPacket[i] = sourceADR[i-5] ;
}
replyPacket[15] = 0 ; // set both options
replyPacket[16] = 0 ;
for (int i =17 ; i < datalen+17 ; i++){
replyPacket[i] = incomeData [i-17]; // add data to packet
}
replyPacket[2] = 14 + datalen ; // set the lower length byte
calcsum = 0; // start calculating errorsum
replyPacket[17 + datalen] = 0;
for (int i = 3 ; i <= replyPacket[2]+3 ; i++){
calcsum = calcsum + replyPacket[i];
}
replyPacket[17 + datalen]= 0xFF - calcsum; // finish packet by adding checksum
Serial.print ("The packet is: "); // start printing raw packet before sending
for (int i = 0 ; i < replyPacket[2]+3 ; i++){
Serial.print (replyPacket[i],HEX);
Serial.print (' ');
}
Serial.println (replyPacket[17 + datalen],HEX); // finish printing packet
Serial.println ("Sending Packet"); // start sending packet to original source
 
Search WWH ::




Custom Search