calculating check sum

I'm sending serial packets to control a motor driver. Each packet needs the final byte to be a check sum. When all bytes and the check sum value are added together, the hex number ends in 00. I need my program to calculate these check sums.

a packet is an array that looks like this
int packet[] = {0x00, 0x10, 0x00, 0x86, 0x6A};
in the example, 6A is the checksum. (10 + 86 + 6A = 100)

if i change the values of the packet, I need to calculate a correct checksum.
here is my example code, with a line of imaginary code doing the part i don't know how to do

//takes as input a packet whose check sum needs to be recalculated
//and the size of the packet in bytes

int* calcCheckSum (int* pack, int packSize) {
  int sum = 0;
  for (int i=0; i < (packSize-1); i++) {
       sum = pack[i] + sum;
       }
  sum = last two digits of sum in hex;
  pack[packSize-1] = 100 - sum;
  return pack;
}

try this?

int * calcCheckSum (int* pack, int packSize) {
  int sum = 0;
  for (int i=0; i < (packSize-1); i++) sum += pack[i];
  [glow]sum = sum & 0xFF;[/glow]
  pack[packSize-1] =[glow] 0x100 - sum;[/glow]
  return pack;
}

(not tested)

I wouldn't bother reinventing the wheel in such a sub-optimal way. avr-libc comes with an optimized crc16 function built-in:

http://www.nongnu.org/avr-libc/user-manual/group__util__crc.html

[edit]
This will only work if you have control of both ends of the wire :wink:

@tylerwalker:

int* calcCheckSum (int* pack, int packSize)

If you are sending and receiving bytes, then why are you using an array of ints?

Just do everything with bytes and the math takes care of itself!

void setup()
{
    Serial.begin(9600);
}

byte pack[5] = {0x00, 0x10, 0x00, 0x86, 0x6A};
int pack_size = 5;

void loop()
{
    byte sum = 0;
    for (int i = 0; i < pack_size-1; i++) {
        sum += pack[i];
    }
    Serial.print("Sum of received data bytes                       = ");
    printhexbyte(sum);

    byte calculated_cksum = -sum;
    Serial.print("Calculated checksum                              = ");
    printhexbyte(calculated_cksum);
    
    byte crcbyte = pack[pack_size-1];
    Serial.print("Received checksum byte                           = ");
    printhexbyte(crcbyte);
    
    byte overall = sum+crcbyte;
    Serial.print("Sum of received data bytes and received checksum = ");
    printhexbyte(overall);
    Serial.println();
    
    delay(1000);
}

void printhexbyte(byte x)
{
    Serial.print("0x");
    if (x < 16) {
        Serial.print('0');
    }
    Serial.print(x, HEX);
    Serial.println();
}

Output:


[color=#0000ff]Sum of received data bytes                       = 0x96
Calculated checksum                              = 0x6A
Received checksum byte                           = 0x6A
Sum of received data bytes and received checksum = 0x00[/color]

Regards,

Dave