Skip to main content

To ensure message data integrity, it is advisable to implement code that checks for serial port (UART) framing errors in addition to the verifying the message CRC. If the CRC in the received message does not match the CRC calculated by the receiving device, the message should be ignored. The C language code snippet below shows how to compute the Modbus message CRC using bit-wise shift and exclusive OR operations. The CRC is computed using every byte in the message frame except for the last two bytes which comprise the CRC itself.

      // Compute the MODBUS RTU CRC
      UInt16 ModRTU_CRC(byte[] buf, int len)
        UInt16 crc = 0xFFFF;
        for (int pos = 0; pos < len; pos++) {
          crc ^= (UInt16)buf[pos];          // XOR byte into least sig. byte of crc
          for (int i = 8; i != 0; i--) {    // Loop over each bit
            if ((crc & 0x0001) != 0) {      // If the LSB is set
              crc >>= 1;                    // Shift right and XOR 0xA001
              crc ^= 0xA001;
            else                            // Else LSB is not set
              crc >>= 1;                    // Just shift right
        // Note, this number has low and high bytes swapped, so use it accordingly (or swap bytes)
        return crc;  

check sum