calculating checksum for API packet - hey johnf

hey Johnf,

in your cookbook, you state to subtract the sum of the payload bytes.

for the Xbee do we have to use that formula type to calculate the checksum?

something like this pseudo code?

  for(i = 3; i < maxsize;i++){

    Checksum = Checksum + data(i)  
  Checksum =  Checksum % 256

or can we use any checksum routine?

This may not answe your question, and Johnf can respond when he sees your question, but the XBee API checksum must be calculated by adding up all the bytes after the frame identifier, then taking the last 8 bits of the value and subtracting that from FF.

So you can’t just use an arbitrary value for the checksum.

Here is an article with an example on how to calculate the checksum. You’ll have to let Johnf answer how that relates to his program. It looks mostly correct from what I can see from your snippet however.


My verbose English version of the checksum generation algorithm (as opposed to the rather condensed version in the cookbook) would be:

  1. Let’s assume you have the packet bytes in an array with the first element at index position 0. The number of bytes (not including the checksum because that hasn’t been calculated yet) is n.
  2. Then add up the values of all the bytes except the first three. (The first three being the frame delimiter 0x7e and the two packet length bytes.)
  3. Take this sum and bitwise AND it with 0xff. Your code says % 256, which is fine and gives the same result.
  4. Now subtract the value obtained in (3) from 0xff. The result of that is the required checksum for the packet, and that’s the bit that was missing from your code.

In C/C++ (untested):
// Assume an array called “packet” with elements of type unsigned char,
// holding n bytes which are the packet contents
// without the checksum.
int sum = 0;
int checksum;
for (int i = 3; i < n; i++) {
sum = sum + packet(i);
sum = sum & 0xff;
checksum = 0xff - sum;

Edit: in the above, packet(i) should use square brackets instead of round brackets. But the forum software seems to interpret square brackets as containers for formatting commands, so I had to change it.

In C/C++ and slightly more efficient, but also untested:
unsigned char checksum = 0xff;
for (int i = 3; i < n; i++) {
checksum -= packet(i);
Proving that the two versions are equivalent is left as an exercise for the reader…

And if that’s not the same as gworle has said - well, one of us is the expert here and it isn’t me :slight_smile:

Message was edited by: johnf


yep, that is how john explained it in his cookbook just needed an extra boost to get me head around it…i think i include the frame id byte. thanks.

that helped. i see my missing link now in my thinking.

just a suggestion, toss something like that in your cookbook in the API sec for calculating the checksum. my brain does much better with visual examples most times.