问题
I'm currently trying to develop an application that uses the Modbus-RTU protocol, and I have to use modbus_tk in Python 2.7.
I'm supposed to use bits of code from another application which is able to communicate with the micro-controller via modbus. It works on that app when I run the following code, but I get an error when I run the same lines in my app.
import modbus_tk
import modbus_tk.defines as cst
import modbus_tk.modbus_rtu as modbus_rtu
import serial
MB_Add_Status = 8 + 5001
def MB_GetStatus(MB_Master_handle):
try:
status = MB_Master_handle.execute(1, cst.READ_HOLDING_REGISTERS, MB_Add_Status, 1)
return status
except modbus_tk.modbus.ModbusError, e:
logger.error("%s- Code=%d" % (e, e.get_exception_code()))
MB_port = 3
masterMB = modbus_rtu.RtuMaster(serial.Serial(port='COM'+str(MB_port), baudrate=19200, bytesize=8, parity='N', stopbits=2, xonxoff=0))
status = MB_GetStatus(masterMB)
First I needed to delete the arguments baudrate
, bytesize
, etc. in the constructor call because it rose an error like :
TypeError: __init__() got an unexpected keyword argument 'stopbits'
But then when we get to the call to execute
, there is an error again, which I couldn't solve yet :
modbus_tk.modbus.ModbusInvalidResponseError: Response length is invalid 0
The only documentation I found is: https://github.com/Nobatek/modbus-tk/tree/master/docs, but I couldn't quite understand much of it. If someone could first explain me what this error really means, and where I should look, this would be highly appreciated. Thank you very much !
回答1:
The right repository for this library is https://github.com/ljean/modbus-tk It requires PySerial 2.7
回答2:
Found it !
I updated the library and set the parameters of the constructor correctly. This works fine know.
来源:https://stackoverflow.com/questions/37720022/cant-connect-to-slave-with-pythons-modbus-tk