beautypg.com

Appendix b. example c code of the ccittcrc, Appendix b. example c code of the ccitt crc – Campbell Scientific CS125 Present Weather Sensor User Manual

Page 53

background image

Appendix B. Example C code of the CCITT
CRC

The code below is provided as an example for programmers implementing their own
code to communicate with the sensor. Users using Campbell loggers can use the
Checksum command in CRBasic to generate a CCITT checksum. Command:
Checksum/ChkSumString,1,0).

The checksum includes all characters excluding the SOT, EOT and the checksum
itself.

The SET and SETNC commands also exclude the two delimiting `:’ characters, one
on each side of the checksum itself.

//----------------------------------------------------------------------------

// Creates a CCITT CRC16 checksum seeded with 0x0000 (XModem style) using a

// fast non table based algorithm.

// Pass in the data to convert into a CRC in the form of a NULL terminated

// character array (a string).

// Returns the CRC in the form of an unsigned 16 bit integer value

// Note: This algorithm has only been tested on a native 16-bit processor with

// a hardware barrel shifter

// All integers are 16-bits long

//----------------------------------------------------------------------------

unsigned int CRC_CCITT(char LineOfData[]){

unsigned int crc; // returned CRC value

unsigned int i; // counter

crc = 0x0000;

// create a check sum for the incoming data

for(i=0;i < strlen(LineOfData); i++){

unsigned crc_new = (unsigned char)(crc >> 8) | (crc << 8);

crc_new ^= LineOfData[i];

crc_new ^= (unsigned char)(crc_new & 0xff) >> 4;

crc_new ^= crc_new << 12;

crc_new ^= (crc_new & 0xff) << 5;

crc = crc_new;

}

return(crc);

}

B-1