Example of CRC-16 Calculation
A message is processed 1 byte at a time in a 16-bit processing register called the CRC register.
1 A default value of FFFF hex is set in the CRC register.
2 An XOR is taken of the contents of the CRC register and the first byte of the message, and the
result is returned to the CRC register.
3 The contents of the CRC register is shifted 1 bit to the right, and 0 is placed in the MSB.
4 If the bit shifted from the LSB is 0, step 3 is repeated (i.e., the contents of the register is shifted
1 more bit).
If the bit shifted from the LSB is 1, an XOR is taken of the contents of the CRC register and
A001 hex, and the result is returned to the CRC register.
5 Steps 3 and 4 are repeated until the contents of the register have been shifted 8 bits to the right.
6 If the end of the message has not been reached, an XOR is taken of the next byte of the
message and the CRC register, the result is returned to the CRC register, and the procedure is
repeated from step 3.
7 The result (the value in the CRC register) is placed in the lower byte of the message.
Example of Appending the Result
If the calculated CRC value is 1234 hex, this is appended as follows to the command frame.
Code: Select all
crc=0xFFFF; //A default value of FFFF hex is set in the CRC register.
LSB=0;
cnt=0;
Serial.print("CRC-");
Serial.println(crc,BIN);
for(i=0;i<13;i++)
{
//An XOR is taken of the contents of the CRC register and the first byte of the message, and the
//result is returned to the CRC register.
//If the end of the message has not been reached, an XOR is taken of the next byte of the
//message and the CRC register, the result is returned to the CRC register, and the procedure is
//repeated from step 3.
crc=crc^data[i];
LSB=crc&1;
cnt=0;
while(cnt<8) //Steps 3 and 4 are repeated until the contents of the register have been shifted 8 bits to the right.
{
crc=crc>>1; //The contents of the CRC register is shifted 1 bit to the right, and 0 is placed in the MSB.
crc=crc&0x7fff;
cnt++;
//LSBe=LSB;
LSB=crc&1;
if(cnt==8)break;
Serial.print("LSB-");
Serial.println(LSB,HEX);
// If the bit shifted from the LSB is 0, step 3 is repeated (i.e., the contents of the register is shifted 1 more bit).
//If the bit shifted from the LSB is 1, an XOR is taken of the contents of the CRC register and
//A001 hex, and the result is returned to the CRC register.
if(LSB==0)
{
crc=crc>>1;
crc=crc&0x7fff;
cnt++;
Serial.print("CRC2-");
Serial.println(crc,BIN);
}
else if(LSB==1)
{
crc=crc^operation;
Serial.print("CRC3-");
Serial.println(crc,BIN);
}
}
}