Hey Everyone,
I have been trying to figure out how to use pymodbus for a while now
but using the examples have only been able to figure out how to write
to a register on a modbus/tcp device, but not read a register. Then i
stumbled into the google groups page here and found a simple example
problem posted here
http://groups.google.com/group/pymodbus/browse_thread/thread/beacc3a72dac9ae7
I used this as a base and built my own modbus read/write program while
ignoring all the example code that came with PyModbus. This simple
code works great and if you want to simply use PyModbus as a tool this
is all you need. I will post my code at the end of my message. I am
using a tri-plc nano as the modbus server that i write to / read from.
Hopefully this will save someone days of frustration trying to
understand PyModbus!
My question now is, could someone explain to me why there is all the
twisted reactor code in the examples if it is not really required
(seemingly)? I am fairly new to python so please excuse my ignorance
if it's something obvious :)
Regards,
Marko
______________________________
#!/usr/bin/env python
from pymodbus.client.sync import ModbusTcpClient as ModbusClient
#assign modbus server connection
TRIPLC = ModbusClient(host='192.168.1.5', port=502)
#send write command to modbus server
#this writes a list of values to consecutive registers
#starting with a register you specify
#syntax: write_registers(register, values*len(values))
#register 1000 = DM[1], 1001 = DM[2] etc
setVals = [ 111 , 222 , 333 , 444 , 555]
register = 1000
TRIPLC.write_registers(register, setVals*len(setVals))
#send a single register write command to modbus server
setVal = 555
register = 1010
TRIPLC.write_register(register, setVal)
#send read command to modbus server
#syntax: read_holding_registers(register, #of registers)
#rr1 reads the multi register write result, rr2 reads single reg
rr1 = TRIPLC.read_holding_registers(1000, len(setVals))
rr2 = TRIPLC.read_holding_registers(1010, 1)
#getRegister is an attribute of pyModbus read_holding_registers method
currentVals = range( len(setVals) )
for i in range( len( setVals ) ) :
currentVals[i] = rr1.getRegister(i)
currentVal = rr2.getRegister(0)
#the below 5 lines are just some result code that you can see in your
command prompt
print currentVals
if (setVals == currentVals) & (setVal == currentVal):
print "successful write"
else:
print "write failed"