GPD315 Modbus RTU Technical Manual TM 4325
Page
19
// *buf pointer to character array that contains the characters to used calculate CRC
// bufLen number of characters to calculate CRC for
// *crc pointer to the array that contains the calculated CRC
void getMBCRC(char *buf, int bufLen, char *crc) {
unsigned long crc_0 = 0xffff; // Declare and initialize variables
unsigned long crc_1 = 0x0000;
int i,j;
for (i=0; i<bufLen; i++) { // Loop through characters of input
array
crc_0 ^= ((unsigned long)buf[i] & 0x00ff); // XOR current character with 0x00ff
for (j=0;j<8;j++) { // Loop through characters bits
crc_1 = (crc_0 >> 1) & 0x7fff; // shift result right one place and
store
if (crc_0 & 0x0001) // if pre-shifted value bit 0 is set
crc_0 = (crc_1 ^ 0xa001); // XOR the shifted value with 0xa001
else // if pre-shifted value bit 0 is not set
crc_0 = crc_1; // set the pre-shifted value equal to
the shifted value
}
}
crc[0] = (unsigned char)((crc_0/256) & 0x00ff); // Hi byte
crc[1] = (unsigned char)(crc_0 & 0x00ff); // Lo byte
return;
}
Figure 4-2 CRC Calculation in C