pythonmodbuspymodbus

Having difficulty reading holding registers with pymodbus


Having difficulty reading holding registers with pymodbus

I'm trying to interface with a cheap benchtop power supply, just running some initial scripts to discern functionality. The OEM provided documentation on their modbus including register addresses here

I can't seem to read the registers using pymodbus with this simple script. Code and output below.

What am I doing wrong? How to better debug? I'm new to modbus.

import time
from pymodbus.client import ModbusSerialClient
from pymodbus.exceptions import ModbusIOException

def run():
        print("Creating client")
        client = ModbusSerialClient("/dev/ttyUSB0", method='rtu', baudrate=9600, stopbits=1, parity='N', bytesize=8, timeout=1)

        print("Connecting to client")
        if not client.connect():
                print("Failed to connect to client")
                return

        # List of register addresses to read from
        register_addresses = [0x0001, 0x0002, 0x0003, 0x0004, 0x0005, 0x0010, 0x0011, 0x0012, 0x0013, 0x0030, 0x0031, 0x0020, 0x0021, 0x0022, 0x0023, 0x9999]

        # Read from each register
        for address in register_addresses:
                try:
                        response = client.read_holding_registers(address, 1)
                        if response.isError():
                                print(f"Error reading register {address}: {response}")
                        else:
                                print(f"Register {address}: {response.registers}")
                        time.sleep(0.035)
                except ModbusIOException as e:
                        print(f"Modbus IO Exception reading register {address}: {e}")

        print("Closing client")
        client.close()

run()

When I run the previous code I get the following output:

ā””ā”€$ python3 modbus4.py
Creating client
Connecting to client
Error reading register 1: Modbus Error: [Input/Output] Modbus Error: [Invalid Message] No response received, expected at least 4 bytes (0 received)
Error reading register 2: Modbus Error: [Input/Output] No Response received from the remote slave/Unable to decode response
...
Error reading register 39321: Modbus Error: [Input/Output] No Response received from the remote slave/Unable to decode response

Solution

  • You need to provide the server/slave ID explicitly in the read_holding_registers command, since you did not do it when initializing the client.

    Try response = client.read_holding_registers(address, count = 1, slave = 1) and see if it replies.

    I'm not 100% sure the server address is 1 though, so you might have to add another for-loop to iterate thru those as well; or dig a bit deeper into the manual, it should have it.