//Using both a direct function and a library
//for CRC16 calculation used in Modbus
#include "CRC16.h"
#include "CRC.h"
byte str[24] = {0x01,0x03,0x02,0x00,0x30};
byte str2[24] = {0x01,0x03,0x00,0x01,0x00,0x01};
CRC16 crc;
void setup()
{
Serial.begin(115200);
Serial.println(__FILE__);
// Serial.println("Verified with - http://zorc.breitbandkatze.de/crc.html \n");
uint16_t crc = ModRTU_CRC(str,5);
Serial.println(crc,HEX);
crc = ModRTU_CRC(str2,6);
Serial.println(crc,HEX);
}
void loop()
{
}
// Compute the MODBUS RTU CRC
uint16_t ModRTU_CRC(byte* buf, int len)
{
uint16_t crc = 0xFFFF;
for (int pos = 0; pos < len; pos++) {
crc ^= (uint16_t)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)
uint16_t crc2 = crc >> 8;
crc2 |= crc << 8;
return crc2;
}
// -- END OF FILE --