Search code examples
pythonmodbuspymodbus

Write a specific bit in a 16bits register with modbus in python


I try to communicate with a m221 module (schneider Electrique) who use modbus protocol. I can read and write value of a register with pymodbus (read_input_register, write_register) but for control the m221 module, I need to set only one bit of register to 1. (Ex : bit 11 of register 10).

anyone know how i can do that or just if it's even possible?


Solution

  • You have to read the 16bit register, modify the bit and write it back. This of course is not an atomic operation so if something else modifies one of the other bits in the middle of your read-modify-write cycle, then you are overwriting their changes.

    Some devices support function 0x16 which is a Mask Write to a register, i.e. AND + OR bitmasks are supplied to indicate which bits in the register are actually being written and then other bits will be left unmodified.

    Edit: actually pymodbus seems to support Mask Write Register.

    To set bit 11 of register 10:

    client.mask_write_register(10, and_mask=0xFFFF, or_mask=0b0000000000100000)
    

    This is assuming bit 11 means the 11th bit counting from MSB towards LSB.