In this lesson, you will learn how to implement the polynomial division logic required to verify a CAN frame’s integrity using the Cyclic Redundancy Check (CRC).
The Concept of Polynomial Division
When a CAN controller sends a message, it treats the data bits as a long binary number—a "polynomial." Before sending, the transmitter divides this number by a fixed "generator polynomial" and keeps the remainder. This remainder is the CRC value appended to the end of the frame.
Upon receiving the frame, the receiver performs the exact same division using the received data bits. If the remainder matches the transmitted CRC, the data is likely error-free. In binary math, this division is performed using XOR (Exclusive OR) operations instead of standard subtraction.
Implementing the CRC Logic
To verify a CAN frame, the receiver runs the incoming bits through a shift register. Every time a bit enters, if the most significant bit is a 1, we XOR the register with the generator polynomial. Here is how that logic looks in code:
uint16_t calculate_crc(uint8_t *data, size_t length) {
uint16_t crc = 0x0000; // Initial value
uint16_t poly = 0xC599; // CAN-standard generator polynomial
for (size_t i = 0; i < length; i++) {
crc ^= (uint16_t)data[i] << 7; // Align data to the register
for (int j = 0; j < 8; j++) {
if (crc & 0x8000) {
crc = (crc << 1) ^ poly;
} else {
crc <<= 1;
}
}
}
return crc & 0x7FFF; // Mask to 15 bits for CAN
}
Detecting the Error
The beauty of this system is its efficiency. The receiver does not need to store the original message to check it. If the receiver calculates a CRC value that differs from the value attached to the frame, it immediately knows a bit-flip occurred during transmission (often due to electromagnetic interference on the differential bus). Because the CAN protocol is robust, the hardware will then trigger an error frame to discard the corrupted data, ensuring that only valid information is processed by your application.
Key Takeaway: The CRC uses XOR-based polynomial division to generate a unique remainder that acts as a digital fingerprint, allowing the receiver to detect any bit-level corruption in the CAN frame.