Ahh - so in my case I was controlling an electricity meter and there were only 4 commands - so I just pulled those - including CRC - out of the datasheet.
So... this would appear to work - at least it produces the values they have in their example:
function addCRC16(buf) {
// https://stackoverflow.com/a/19994882/1215872
var crc = 0xFFFF;
for (var pos=0;pos<buf.length;pos++) {
crc ^= buf[pos]; // XOR byte into least sig. byte of crc
for (var 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
}
}
buf.push(crc&0xFF, crc>>8);
return buf;
}
var message = [0x02, 0x07];
addCRC16(message);
Serial1.write(message);
Espruino is a JavaScript interpreter for low-power Microcontrollers. This site is both a support community for Espruino and a place to share what you are working on.
Ahh - so in my case I was controlling an electricity meter and there were only 4 commands - so I just pulled those - including CRC - out of the datasheet.
But the calculation looks ok - there's even a flowchart on page 40 of https://modbus.org/docs/Modbus_over_serial_line_V1_02.pdf which seems to be implemented in https://stackoverflow.com/a/19994882/1215872
So... this would appear to work - at least it produces the values they have in their example: