Example of calculating a CCITT CRC using C program language

The following code is provided as an example for programmers implementing their own code to communicate with the sensor. Campbell Scientific data logger users can use the checksum command in CRBasic Editor to generate a CCITT checksum. Refer to the downloadable example programs available at www.campbellsci.com/downloads/cs140-program-examples .

The checksum includes all characters after the STX and before the space preceding the checksum.

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);

}