CRC
CRC
CRC in Embedded Programming
CRC is an abbreviation of Cycle Redundancy Check which is used for detecting errors in digital data over the network
CRC is used to check if the data is modified during transmission.
To check integrity, generate CRC before sending the data and receiver can verify the data by comparing CRC.
Compute CRC
- Divide the data by the GENERATOR POLYNOMIAL which is X^16 + x^12 + X^5 + 1 (0x1021).
- The remainder is used to generate CRC.
- XOR and SHIFT operations are needed.
Generate CRC 16
-
Initialise CRC Register to 0xFFFF.
-
Put the data into Data Register.
-
Compare the LSB (Least Significant Bit) of CRC Register and Data Register.
-
If they are the same, SHIFT CRC Register RIGHT.
If they are different, SHIFT CRC Register RIGHT and XOR with GENERATOR POLYNOMIAL
-
Move to the next bit on the Data Register and go to 3.
Programming In C
#define POLY 0x1021
uint16_t generate(uint8_t *data, uint8_t len) {
uint16_t crc = 0;
for(int i = 0; i < len; i++) {
crc = crc ^ ((*data++) << 8);
for(int j = 0; j < 8; j++) {
if(crc & 0x8000) {
crc = (crc << 1) ^ POLY;
}
else {
crc << 1;
}
}
}
return crc;
}