A two byte error checking code is attached to all messages and replies. All characters are included in this check except the lead character, the CRC bytes, and the optional terminator characters. The two byte code is always sent in high byte then low byte order.
After the CRC is initialized to CRC_INIT, the crccitt() function below is used to adjust the CRC value for each data byte sent. The ones complement of the resulting two byte word is placed on the end of the message as the CRC word. The process is repeated at the receiving end, except that the incoming CRC word is added into the calculation. If the result is the value CRC_MAGIC (1D0Fh), then no errors have occurred.
The crc value is kept as a 16 unsigned value. When the crc contains only zero bits, zero data bytes will have no effect on it. We (and almost all other implementations) therefore initialize the CRC value to CRC_INIT (0xffff) so that extraneous leading zeros will be detected.
crccitt() - This function updates a CRC value, using the CRC-CCITT 16 bit CRC polynomial, for a given data byte. The CRC value of type unsigned short should be initialized to the value CRC_INIT found below and in crc.h. The function crccitt() should then be called for each data byte included in the CRC. The sending station then sends the ones compliment of the resulting CRC value, high byte first. The receiving station includes the CRC bytes in its CRC computation and compare the result with the value CRC_MAGIC found below and in crc.h.
CRC_INIT is FFFFh (65535 decimal)
CRC_MAGIC is 1D0Fh (7439 decimal)
#include <crc.h> /* supplied with the sample program */
unsigned crccitt(
unsigned crc, /* old crc value */
unsigned char data /* data byte */
);
Return value: new CRC value
Example:
/* This code is for the sending station */
#include <stdlib.h>
unsigned crc; /* crc value */
char buf[100]; /* buffer to send */
int i; /* work variable */
...
crc = CRC_INIT; /* initialize crc */
for (i=0;i<100;i++) {
crc = crccitt(crc,buf[i]);
/* send buf[i] here */
}
crc = ~crc; /* do ones compliment */
/* send high byte of crc, (crc >> 8) */
/* send low byte of crc, (crc & 0xff) */
/* This code is for the receiving station */
#include <stdlib.h>
unsigned crc; /* crc value */
char buf[102]; /* receive buffer */
int i; /* work variable */
...
crc = CRC_INIT; /* initialize crc */
for (i=0;i<102;i++) {
/* receive buf[i] here */
crc = crccitt(crc,buf[i]);
}
if (crc == CRC_MAGIC)
/* crc check ok */
else
/* an error was detected */