Jan
Jan

Reputation: 11

How to read slave modbus holding registers by pymodbus?

I am trying to read holding registers over Modbus RTU with python. I can make it work with the minimalmodbus library, but not with the pymodbus library.

What has so far worked is the minimalmodbus library:

`import minimalmodbus

PORT='com5'
A_REGISTER = 40320
B_REGISTER  = 40321
OFFSET = 38001

A_REGISTER =A_REGISTER - OFFSET
B_REGISTER =B_REGISTER - OFFSET

#Set up instrument
instrument = minimalmodbus.Instrument(PORT,1,mode=minimalmodbus.MODE_RTU)

#Make the settings explicit
instrument.serial.baudrate = 19200        # Baud
instrument.serial.bytesize = 8
instrument.serial.parity   = minimalmodbus.serial.PARITY_EVEN
instrument.serial.stopbits = 1
instrument.serial.timeout  = 1          # seconds

#Good practice
instrument.close_port_after_each_call = True

instrument.clear_buffers_before_each_transaction = True

#Read temperatureas a float
#if you need to read a 16 bit register use instrument.read_register()
A_reg = instrument.read_float(A_REGISTER)

#Read the humidity
B_reg = instrument.read_float(B_REGISTER)

#Pront the values
print('The A register value is : %.1f deg C\r' % A_reg)
print('The B rgister value is: %.1f percent\r' % B_reg)
`

This works very well.

However when I try to connect to the exact same modbus slave, using the exact same physical setup, reading the same register, but using the pymodbus library, with the following code, it doesn't work:

`from pymodbus.client import ModbusSerialClient
from pymodbus.transaction import ModbusRtuFramer as ModbusFramer

client = ModbusSerialClient(
    framer=ModbusFramer,
    method='rtu',
    port='COM5',
    baudrate=19200,
    bytesize=8,
    parity="E",
    stopbits=1,
    retries = 5,
    timeout=1 
     )

client.strict = False
client.connect()

res = client.read_holding_registers(address=B_REGISTER, count=1, unit=1)
res.registers`

Most of the time I get the following error: ConnectionException: Modbus Error: [Connection] Failed to connect[ModbusSerialClient(<pymodbus.framer.rtu_framer.ModbusRtuFramer object at 0x0000021CE12F2EE0> baud[19200])]

But a few times I get [0]

Any good ideas? I have been reading quite a bit on Stackoverflow and other sources, but I can't figure out what I am doing wrong.

Upvotes: 1

Views: 1299

Answers (0)

Related Questions