Calculate 8 Bit Checksum on 22 Byte Array?

I'm trying to calculate a simple 8 bit checksum on a 22 byte array sent across the serial line.

The structure for the communication is as follows:

Byte[0] = 255
Byte [1] - [20] = Data (values 0-254)
Byte [21] = Checksum

On the receiver, it states the checksum is calculated as as the sum of all bytes, however i'm calculating different values then the receiver is calculating. I thought perhaps it could be because of byte overflow?

Can anyone point out what i am doing wrong?

byte chk = 0;
  for ( int i=0; i<length; i++)
    chk += data[i];

You didn't show us where length is defined or how it gets its value.

Show us your values and what the receiver calculates.

Is 'length' the length of the entire message, including the checksum?

If you are receiving an Intel-hex formatted file, then calculate the CHKSUM in the following way:

Given below a real example of an Intel-hex frame received over USART Port on 30/6/2005:


: 10 C100 00 003E9032002116101E110133C10ACD19 D4
(a) (b) (c) (d) (e) <---------------------------------------> (f)

(a) indicates that a new data frame to begin.

(b) indicates number of information bytes contained in field (e) = 10h = 16 byte

(c) indicates the starting location of RAM space into which the data byte to be stored

(d) indicates (if 00) not the end-of-file; more frames are to arrive.

(e) indicates information (data) bytes contained in the current frame,

(f) indicated CHKSUM. It is calculated in the following way:
all data bytes from and including field (b) to field (e) are added. The carry is discarded. Two's complement of the remaining 8-bit is taken as CHECKSUM, and it is transmitted as the last byte of the frame.

(1) The frame contains 22 bytes data including all fields.

(2) Field-(a) and Field-(f) will not be taken into account to calculate CHKSUM.

(3) Your codes:

byte chk = 0;
for ( int i=0; i<length; i++)   //length = 19 (22-02 = 20 - 1)
    chk += data[i];    

//sum=10+C1+00+00+00+3E+90+32+00+21+16+10+1E+11+01+33+C1+0A+CD+19 = 042C
//discard accumulated carries; we get 2C = 0010 1100
//take 2's complemet code : 1101 0011 + 1 = D4 

//----take the 2's complement of chk; you will get D4-----

chk = (chk^0xFF);  //chk = D3
chk +=chk+01;      //chk = D4