#include <stddef.h>
#include <stdint.h>
/* CRC-16/MODBUS: init 0xFFFF, reflected polynomial 0xA001, wire order Lo then Hi */
uint16_t modbus_crc16(const uint8_t *buf, size_t len) {
uint16_t crc = 0xFFFFU;
for (size_t i = 0; i < len; ++i) {
crc ^= (uint16_t)buf[i];
for (int bit = 0; bit < 8; ++bit) {
if (crc & 0x0001U) crc = (uint16_t)((crc >> 1) ^ 0xA001U);
else crc >>= 1;
}
}
return crc;
}
/* Test vector: 01 04 00 10 00 02 70 0E (CRC=0x0E70, wire: 0x70 0x0E) */
static const uint8_t frame_pdu[6] = { 0x01, 0x04, 0x00, 0x10, 0x00, 0x02 };
def modbus_crc16(data: bytes) -> int:
crc = 0xFFFF
for b in data:
crc ^= b
for _ in range(8):
crc = ((crc >> 1) ^ 0xA001) if (crc & 1) else (crc >> 1)
return crc & 0xFFFF
pdu = bytes.fromhex("01 04 00 10 00 02")
crc = modbus_crc16(pdu)
rtu_frame = pdu + crc.to_bytes(2, "little")
assert rtu_frame.hex(" ").upper() == "01 04 00 10 00 02 70 0E"
print(rtu_frame.hex(" ").upper())
Modbus RTU transmits the CRC low byte first, followed by the high byte, whereas multi-byte register addresses and values are big-endian.
Poll read-only telemetry with Modbus FC04 Input Registers
Smart AC energy meters (such as SDM120/SDM630), temperature transmitters and flow sensors expose live read-only measurements in the 3xxxx Input Register bank accessed via Function Code 0x04.
Many sensors pack IEEE-754 32-bit floats across two consecutive 16-bit registers (quantity = 2). Generate the exact 8-byte hex poll packet and CRC-16 here.