Chapter 6. Serial I/O, SNP & RTU Protocols
GFK-2222AD
April 2018
233
Calculating the CRC-16
The pseudo code for calculation of the CRC-16 is given below.
Preset byte count for data to be sent.
Initialize the 16-bit remainder (CRC) register to all ones.
XOR the first 8-bit data byte with the high order byte of the 16-bit CRC register. The
result is the current CRC.
INIT SHIFT:
Initialize the shift counter to 0.
SHIFT:
Shift the current CRC register 1 bit to the right.
Increment shift count.
Is the bit shifted out to the right (flag) a 1 or a 0?
If it is a 1, XOR the generating polynomial with the current CRC.
If it is a 0, continue.
Is shift counter equal to 8?
If NO, return to SHIFT.
If YES, increment byte count.
Is byte count greater than the data length?
If NO, XOR the next 8-bit data byte with the current CRC and go to INIT SHIFT.
If YES, add current CRC to end of data message for transmission and exit.
When the message is transmitted, the receiver performs the same CRC operation on all the data bits
and the transmitted CRC. If the information is received correctly the resulting remainder (receiver CRC)
is 0.
Sample CRC-16 Calculation
The RTU device transmits the rightmost byte (of registers or discrete data) first. The first bit of the CRC-
16 transmitted is the MSB. Therefore, in the example the MSB of the CRC polynomial is to the extreme
right. The X
16
term is dropped because it affects only the quotient (which is discarded) and not the
remainder (the CRC characters). The generating polynomial is therefore 1010 0000 0000 0001. The
remainder is initialized to all 1s.
In this example, the CRC-16 is calculated for RTU message, Read Exception Status 07. The message
format is as follows:
Address
Function
CRC-16
01
07
In this example, device number 1 (address 01) is queried. You need to know the amount of data to be
transmitted and this information can be found for every message type in
Calculating the Length of Frame
For this message the data length is 2 bytes.