FixCDAB / ABCDModbus TCP / pymodbus
Fix: Garbage Float Values When Reading 32-Bit Modbus Registers in Python
Quick fix for IEEE 754 byte/word-order mismatches (ABCD vs. CDAB) when unpacking 32-bit REAL tags from PLCs with pymodbus and Python struct.
2 min read
Symptom: Reading a 32-bit REAL value (two contiguous 16-bit holding registers) from a PLC or VFD over Modbus TCP returns wild scientific-notation garbage such as 1.84e-39 or 7.42e+22 instead of the expected engineering value (123.45).
Verify Word Order with a Known Test Constant
Write 123.45 (0x42F6E666) into a spare REAL register on the PLC and read both 16-bit holding registers (reg[0], reg[1]) in hex:
Observed Registers ([reg0, reg1]) |
Layout | Description | Python Unpack Pattern |
|---|---|---|---|
['0x42f6', '0xe666'] |
ABCD |
Big-endian bytes, big-endian words | struct.pack(">HH", r0, r1) -> ">f" |
['0xe666', '0x42f6'] |
CDAB |
Big-endian bytes, swapped words (most common mismatch) | struct.pack(">HH", r1, r0) -> ">f" |
['0xf642', '0x66e6'] |
BADC |
Byte-swapped inside each register | struct.pack("<HH", r0, r1) -> ">f" |
['0x66e6', '0xf642'] |
DCBA |
Full little-endian | struct.pack("<HH", r0, r1) -> "<f" |
The Fix (Explicit struct Unpacking)
Do not rely on deprecated BinaryPayloadDecoder helpers from older pymodbus versions. Swap the 16-bit register pair explicitly before unpacking IEEE 754 floats:
import structfrom typing import Literal
WordOrder = Literal["ABCD", "CDAB", "BADC", "DCBA"]
def decode_float32(reg0: int, reg1: int, order: WordOrder = "CDAB") -> float: if order == "ABCD": raw = struct.pack(">HH", reg0, reg1) elif order == "CDAB": raw = struct.pack(">HH", reg1, reg0) elif order == "BADC": raw = struct.pack("<HH", reg0, reg1) elif order == "DCBA": return struct.unpack("<f", struct.pack("<HH", reg0, reg1))[0] else: raise ValueError(f"Unsupported word order: {order}")
return struct.unpack(">f", raw)[0]
# Example: PLC holding registers [0xE666, 0x42F6] -> 123.45print(round(decode_float32(0xE666, 0x42F6, order="CDAB"), 2))