Skip to content

Reading coil data bits is reversed #38

Open
vladimir1284/micropython-modbus
#1
@brainelectronics

Description

@brainelectronics

Found during resolving #36

Setting up a coil with the following data and reading the coil states returns 1100 1101 instead of expected 1011 0011 as setup. This issue was covered by the limit of only reading up to 8 coils in a row. And due to the bad unittest, not covering this case.

{
    "COILS": {
        "MANY_COILS": {
            "register": 150,
            "len": 19,
            "val": [
                1, 0, 1, 1, 0, 0, 1, 1,
                1, 1, 0, 1, 0, 1, 1, 0,
                1, 0, 1
            ],
            "description": "Modbus_Application_Protocol_V1_1b3 Read Coils example"
        }
    }
}
b'\xCD\x6B\x05',
[
            # 20, 21,    22,   23,   24,    25,    26,   27
            True, False, True, True, False, False, True, True,
            # 28, 29,   30,    31,   32,    33,   34,   35
            True, True, False, True, False, True, True, False,
            # 36, 37,    38
            True, False, True
]

Reason/root cause
Not sure yet, but it might be due to

if function_code in [Const.READ_COILS, Const.READ_DISCRETE_INPUTS]:
sectioned_list = [value_list[i:i + 8] for i in range(0, len(value_list), 8)] # noqa: E501
output_value = []
for index, byte in enumerate(sectioned_list):
# see https://github.com/brainelectronics/micropython-modbus/issues/22
# output = sum(v << i for i, v in enumerate(byte))
output = 0
for bit in byte:
output = (output << 1) | bit
output_value.append(output)
fmt = 'B' * len(output_value)
return struct.pack('>BB' + fmt,
function_code,
((len(value_list) - 1) // 8) + 1,
*output_value)
which is of course the only untested function of functions.py. In particular the constructed output_value is mixing up LSB and MSB.

The status of outputs 27–20 is shown as the byte value CD hex, or binary 1100 1101. Output 27 is the MSB of this byte, and output 20 is the LSB.

Taken from Modbus Application Protocol, chapter 6.1 01 (0x01) Read Coils

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingclientClient implementation specific issue

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions