Page 33/37 – Xylem Expert 7060_7070_Modbus User Manual

Page 27

Advertising
background image

Communication protocol Serie30

Page 33/37

6.4

Calculation of the CRC16 checksum

The checksum can either be calculated or derived from a table.

Here is an example of CRC16 calculation in C:

//////////////////////////////////////////////////////////////////////////

// CRC-16 calculation in C

//

// Calculation of CRC-16 checksum over an amount of bytes in the serial buffer.

// The calculation is done without the 2byte from crc16 (receive-mode).

// SC_Buffer[]: Byte-Buffer for the serial interface. Type: unsigned char (8bit)

// SC_Amount : Amount of Bytes which should be transmitted or are received (without CRC16)

//

//////////////////////////////////////////////////////////////////////////

void CalcCRC16(unsigned char* CRC_H, unsigned char* CRC_L)

{

CRC := $FFFF

N := 0

M := 0

CRC mod 2

= 1

CRC := CRC div 2

CRC := CRC xor $A001

CRC := CRC div 2

M < 8

M := M + 1

N := N + 1

N < Message

l

th

START

STOP

CRC := CRC xor DATA[N]

yes

yes

yes

// locals

unsigned int Crc;

unsigned char n, m, x;

// initialisation

Crc= 0xFFFF;

m= SC_Amount;

x= 0;

// loop over all bits

while(m>0)

{

Crc^= SC_Buffer[x];

for(n=0; n<8; n++)

{

if(Crc&1)

{

Crc>>= 1;

Crc^= 0xA001;

}

else

Crc>>= 1;

}

m--;

x++;

}

// result

*CRC_H= (Crc>>8)&0xFF;

*CRC_L= Crc&0xFF;

}// end CalcCRC16

This results in the following calculation for function 48 with device address 250: CRC16_H= 4, CRC16_L= 67.

Examples showing use based on a table are to be found in the MODBUS documentation at:

http://www.modbus.org

Advertising