Calculating Modbus CRCs

Introduction

Modbus RTU (serial) requires a 16-bit CRC calculation following every Modbus RTU payload. To calculate that 16-bit CRC, the SeaMAX uses the following code:

  unsigned short calc_crc(int n,unsigned char *outbound_message) 
  { 
    unsigned char carry_flag; 
    unsigned short crc=0xFFFF; 

    for (int i = 0; i < n; i++) 
    { 
      crc = crc ^ outbound_message[i]; 

      for (int j = 0; j < 8; j++) 
      { 
        carry_flag = crc & 0x01; 
        crc = crc >> 1; 

        if (carry_flag == 1) 
        { 
          crc = crc ^ 0xA001; 
        } 
      } 
    } 

    return crc; 
  } 
 
 
Generated on Mon Oct 3 2022.