CONTREX CX-1200 User Manual

Page 273

Advertising
background image

7 - 34

Example of CRC-16 Calculation (in C):

#define CRC16 0x8005

/* CRC-16 Generating Poly */

/* function returns the accumulated CRC value calculated for the Buffer */
/* this value can be transmitted or compared to a CRC value received */
/* “*data” is a pointer to the Buffer of data bytes to calculate the CRC for */
/* “len” is the number of data bytes to use for the calculation */

unsigned int do_crc(unsigned char *data, int len)
{

int i, j;

/* byte & bit counters */

unsigned int accum = 0xFFFF;

/* CRC value accumulator */

unsigned int dat;

/* holds data byte */

for(i = 0; i < len; ++i){

/* for each byte of data */

dat = *data++;

/* get data byte & goto next */

accum ^= (dat << 8);

/* put data into high byte */

j = 0;

/* clear bit counter */

while(j++ < 8){

/* for each bit */

if(accum & 0x8000)

/* if MSB set */

accum ^= CRC16;

/* Modulus-2 math w/CRC 16 */

accum <<= 1;

/* shift left 1 bit */

}

/* end for each bit */

}

/* end for each byte */

return(accum);

/* return the CRC value */

}

/* End do_crc function */

Note:

This “CRC” must be converted to 4 ASCII characters before transmission. (Chars 0 to 9 and A to F
should be used). For all “ASCII HEX” values the A through F characters must be in Upper Case
when Transmitted in order to keep the conversions consistent.

Advertising