Crc-16 calculation example - c, Message formats 2-12 – Yaskawa F7 Modbus User Manual

Page 29

Advertising
background image

Message Formats 2-12

CRC-16 Calculation Example - C

void

getMBCRC(char *, int, char *)

// function prototype

void

getMBCRC(char *buf, int bufLen, char *crc) { // Function name and parameter list returning a void

// *buf

pointer to character array used to calculate CRC

// bufLen

number of characters to calculate CRC for

// *crc

pointer to the array that contains the calculated CRC

unsigned long crc_0 = 0xffff;

// Declare and initialize variables

unsigned long crc_1 = 0x0000;

// Declare and initialize variables

int

i,j;

//

Declare

and

initialize

variables

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

}

// End for loop - Loop through characters bits

}

// End for loop - Loop through characters of input array

crc[0] = (unsigned char)((crc_0/256) & 0x00ff);

// Hi byte

crc[1] = (unsigned char)(crc_0 & 0x00ff);

// Lo byte

return;

//

Return

to

calling

function

} //

End

of

CRC

calculation

function

Figure 2.2 – CRC-16 Calculation in C

Advertising
This manual is related to the following products: