Skip to content

Instantly share code, notes, and snippets.

@Nsk1107
Last active March 7, 2019 08:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Nsk1107/c0875a55a5d30e00313d6de0930976bf to your computer and use it in GitHub Desktop.
Save Nsk1107/c0875a55a5d30e00313d6de0930976bf to your computer and use it in GitHub Desktop.
CRC16 calculation for Modbus RTU
//data[] is byte array to calculate CRC16
byte res[8]; //result is stored in this array
void ModRTU_CRC(byte data[]) {
uint16_t crc = 0xFFFF;
for (int pos = 0; pos < 6; pos++) { //6 is data array length
res[pos] = data[pos];
crc ^= (uint16_t)data[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
}
}
res[6] = lowByte(crc);
res[7] = highByte(crc);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment