MAS7.1 Supplemental Guide, Rev 1.1, 9/28/07
31
K.I.S.S.™
Keep It Simple Serial
Source Code Example of Calculating a CRC-8 Checkcode
The following is a simple “C” program that calculates the CRC-8 of the string “TestString” and then prints the
initial string with the calculated CRC-8 checkcode appended to it.
You can download this source code at:
http://www.zektor.com/downloads/crc8tst.c
#include "stdio.h"
// Routine for updating the CRC-8 checkcode using a polynomial
// of: x^8 +x^6 +x^3 +x^2 + 1.
//
// To create the CRC8_POLY mask, we start by ignoring the highest
// bit (x^8) since it is assumed to always be 1 and lies outside
// our byte boundary, and doesn't affect our results.
//
// The rest of the bits of the polynomial are reversed from the
// polynomial's order. This allows us to read in each bit starting
// with bit 0 of each byte, instead of bit 7. This is done because
// the UART sends its LSB first and by doing the same we are able to
// preserve the CRC's burst error detection characteristics.
//
// So:
// x^8 +x^6 +x^3 +x^2 + 1 = 101001101 = 14D hex
// Ignore X^8: 01001101 = 4D hex
// Reverse bit order: 10110010 = B2 hex
#define CRC8_POLY 0xB2 // polynomial mask
#define CRC8_INIT 0xFF // initial value
void crcByte( unsigned char *crc8, char cc)
{
unsigned char lcrc8; // local copy of CRC-8 value
int bitcount;
lcrc8 = *crc8; // get local copy of CRC-8
// update CRC-8 with 8 new bits
lcrc8 ^= cc; // test each bit against CRC-8
for (bitcount = 0; bitcount < 8; b+)
{
// if resultant bit was a 1, shift and xor in mask
// else, just shift
if (lcrc8 & 0x01)
lcrc8 = ((lcrc8 >> 1) & 0x7F) ^ CRC8_POLY;
else
lcrc8 = (lcrc8 >> 1) & 0x7F;
}
*crc8 = lcrc8; // return new CRC8
}