Hello,
I'm doing a modbus RTU communication protocol...
the function for calculating the CRC I came across a strange effect.
The function returns an incorrect value and I don't know why.
The same function returns a correct value if I change the data (see BYTE nr. 9).
char test1[14]= {0x00,0x00,0x32,0x00,0x00,0x00,0x00,0x00,0x80,0x02,0x00,0x00,0x00,0x00};
char test2[14]= {0x00,0x00,0x32,0x00,0x00,0x00,0x00,0x00,0x7F,0x02,0x00,0x00,0x00,0x00};
void loop(){
Serial.print(crc_calc(test1,14), HEX);
Serial.print(crc_calc(test2,14), HEX);
}
uint16_t crc_calc(char *pcode , uint16_t len) {
uint16_t crc=0xFFFF; //Inizializzazione del registro CRC con tutti '1'
int z;
int y;
for(z=0;z < len; z++) {
crc = crc ^ (uint16_t)pcode[z];
for(y=0; y < 8; y++) {
if((crc & 0x0001) != 0) crc = (crc >> 1) ^ 0xA001;
else crc = (crc >> 1);
}
}
return crc;
}
test1 return 0x9260 and is not correct ....
the correct value for CRC-16 modbus is 0x8674 .
test2 return 0x8960 and is correct, look at the calculator at the following link:
Copy and paste one at a time next sequence of byte.
Set HEX and try.
test1) --> 00 00 32 00 00 00 00 00 80 02 00 00 00 00
test2) --> 00 00 32 00 00 00 00 00 7F 02 00 00 00 00
someone found the error?