#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 06 20 00 13 88 8F 5C (CRC=0x5C8F, wire: 0x8F 0x5C) */
static const uint8_t frame_pdu[6] = { 0x01, 0x06, 0x20, 0x00, 0x13, 0x88 };
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 06 20 00 13 88")
crc = modbus_crc16(pdu)
rtu_frame = pdu + crc.to_bytes(2, "little")
assert rtu_frame.hex(" ").upper() == "01 06 20 00 13 88 8F 5C"
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.
Send single-register control writes with Modbus RTU FC06
Function Code 0x06 writes a single 16-bit unsigned integer into a holding register—commonly used to command VFD motor frequency (e.g., 5000 = 50.00 Hz), toggle control words or update PID setpoints.
Unlike read requests, a compliant Modbus slave echoes back the exact same 8-byte FC06 frame verbatim upon success, making loopback CRC verification straightforward.