Hardware Reference
In-Depth Information
The last thing that the update function performs is to check for incoming data on the serial connection. Part 3 is
the function that performs the check for incoming packets. The function tries to capture a complete packet from the
XBee module and check to see if the packet has the correct checksum before attempting to read what the packet is
and performing an action based on the packet's information. The capture length is calculated by the first two bytes
received after the packet start byte, not by the amount of available serial data. The buffer is cleared after each packet
is captured and read. To attempt to keep the serial data incoming constantly, the buffers are cleared and variables
reinitialized if an incoming packet is malformed.
Listing 8-1. testApp.cpp, Part 3 of 7
void testApp::CheckForIncoming(){
incomingPacketChecksum = 0;
incomingByteLen = 0;
if (serial.available() && 0x7E == (incomingBuffer[0] = serial.readByte())){
printf ("Incoming packet \n");
incomingBuffer[1] = serial.readByte(); // pull packet length
incomingBuffer[2] = serial.readByte();
incomingByteLen = incomingBuffer[1] + incomingBuffer[2];
for (int i = 3; i <= incomingByteLen + 3; i++){ // receive the rest of the packet's data
incomingBuffer[i] = serial.readByte();
incomingPacketChecksum += incomingBuffer[i]; // add byte to checksum calculation
}
incomingPacketChecksum = (0xFF - incomingPacketChecksum);
incomingByteLen += 3;
if (incomingByteLen > 0 &&
incomingPacketChecksum == incomingBuffer[incomingByteLen + 1 ] ){
printf ("Has Corect Checksum \n");
ReadPacket();
serial.flush(true, true); // flush incoming and outgoing serial buffers
}
else {
printf ("Check Sum Error\n");
serial.flush(true, true);
incomingByteLen = 0;
incomingPacketChecksum = 0;
for (int i = 0; i <= 80; i++){
incomingBuffer[i] = 0;
}
} // end the error else statement
} //end if (serial.available() && 0x7E ==...
} // end testApp::CheckForIncoming()
The function in part 4 reads the packet when called via a switch statement to determent the packet type and
associated method of reading. This function responds to three different packet types: an AT command response
packet, a transmit response, and a data packet and announces that the packet type is unknown in response to all other
packet types. The program uses data packets transmitted for the Arduino to determine if the packet was sent properly;
if the packet is returned “BAD,” the program resends the packet till an “OK” is returned. This is a simplified method of
error correction that is handled by the next function.
 
Search WWH ::




Custom Search