Search code examples
pythontcpmodbusmodbus-tcppymodbus

Is it possible to write to multiple coils using pyModbusTCP library


There is a method from the documents that looks like client.write_coils(1, [True]*8)

My assumption is that this will write True 8 times because how do I supply a list of addresses? I want to supply a list of 8 modbuss address and assign them all True, for the sake of example. The alternate way is use the singular write_coil from a loop, but since write_coils exists in the docs I am assuming it is the better solution


Solution

  • I agree that the documentation for write_multiple_coils(addr, values) is ambiguous.

    You can look at the Modbus specification for Write Multiple Coils (function code 0x15) which says:

    Writes each coil in a sequence of coils to either ON or OFF.

    So it might be helpful to think of the address as the starting address. So if your starting address is 1 and values is [1,1,1,1,1,1,1,1], you'll write True to Coils 1 through 8. You could manually iterate through the values if you'd prefer, that's what the example code does.

    You can also look at the source code for the function:

    One of the error checks also makes this plain:

    if int(bits_addr) + len(bits_value) > 0x10000:
        raise ValueError('write after end of modbus address space') 
    

    If you try to write [1,1,1] to address 0x9999 you'll trigger this exception.