Search code examples
pythonraspberry-piiotmodbuspymodbus

Pymodbus – Listen for input change on PLC device


I am programming a PLC device (Moxa ioLogik E1214) and have connected the DI ports to buttons, and the coils are connected to LED lights. The idea is that when you press a button, the LED should light up.

I have gotten the program to work if you hold down the button until the read input function executes. The problem is that I'd like to set a time frame (X seconds) and if the button is pressed (and not held down) within this timeframe the light should toggle.

The code is below:

import time
import logging
logging.basicConfig()
log = logging.getLogger()
log.setLevel(logging.DEBUG)

from pprint import pprint
from pymodbus.client.sync import ModbusTcpClient as ModbusClient

moxaA = ModbusClient('XX.XX.XX.XX', port=502)

print "Press a button now"

time.sleep(2)
result = moxaA.read_input_registers(0x30, 1)
if result:
    pressedBtn = result.registers[0]
    if pressedBtn == 1:
        moxaA.write_coil(0, 1)
    else: 
        moxaA.write_coil(0, 0)

As you can see I've set a timeout for the reading of the input registers. But how can I "listen" for an input change within these seconds, and not have to hold the button down until the read input registers function executes?

Thanks in advance


Solution

  • You forgot some arguments (unit, connect, isError()).


    I improved your snippet code:

    moxaA = ModbusClient('XX.XX.XX.XX', port=502)
    
    if moxaA.connect()
        print "Press a button now"
        time.sleep(2)
        result = moxaA.read_input_registers(0x30, 1, unit=1)
    
        if not result.isError():
            pressedBtn = result.registers[0]
    
            if pressedBtn == 1:
                moxaA.write_coil(0, 1, unit=1)
            else: 
                moxaA.write_coil(0, 0, unit=1)
    

    [NOTE]:

    • With the above sleep(2) you should press the button 2 seconds or after 2 seconds.
    • isError() defined in the pymodbus 1.4.0 and above.
    • You should specify the unit, in many cases unit is equal 1.