Skip to content

Instantly share code, notes, and snippets.

@mhutchins
Created July 23, 2018 15:09
Show Gist options
  • Save mhutchins/1b948949c03c23d007c1bdac1ca2c11d to your computer and use it in GitHub Desktop.
Save mhutchins/1b948949c03c23d007c1bdac1ca2c11d to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdint.h>
uint16_t crc16modbus(uint8_t *data, uint16_t len)
{
uint16_t poly = 0xA001;
uint16_t crc = 0xffff;
uint8_t *ptr = data;
while(len--)
{
crc ^= (0xFF & *ptr++);
for (uint8_t i = 0 ; i < 8 ; i++)
{
if (crc & 0x0001)
crc = ((crc >> 1) & 0xFFFF) ^ poly;
else
crc = ((crc >> 1) & 0xFFFF);
}
}
return crc;
}
int main(int argc, char *argv[])
{
uint8_t instr[]={0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39 };
printf("CRC: 0x%04x\n", crc16modbus(instr, sizeof(instr)));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment