我对pymodbus相当陌生,我正在尝试读取带有pymodbus的协作机器人的持有寄存器,以获得当前z坐标的值。这些资料载于7053个地址。我看了以前的问题,但我的代码无法工作:
from pymodbus.client.sync import ModbusTcpClient
host = '192.168.250.201' # Robot IP address
port = 502 # port
client = ModbusTcpClient(host, port)
client.connect()
request = client.read_holding_registers(
address=0x03, # The starting address to read from
count=4, # The number of registers to read
unit=1) # The slave unit this request is targeting
response = client.execute(request)
print(response.bits[0])
client.close()
我一直收到这样一条错误信息:
ConnectionException: Modbus错误:connectModbusTcpClient连接失败(192.168.250.201:502)
我猜我的代码一定有问题,或者可能是其他原因阻止了我建立连接。有什么建议吗?谢谢
发布于 2019-11-14 05:42:03
你有几个小问题:
1)您正在查询的寄存器的地址似乎不正确,请仔细检查设备的手册,以确定您是否正在读取正确的地址,很可能需要查询address=7053
。
2)您正在读取保存寄存器,但随后尝试以线圈(位)打印值。检查它们是否真正持有寄存器,并使用print(response.registers[0])
发布于 2019-11-14 10:27:00
我按照上面的建议修正了我的代码,我还添加了2行代码来尝试解码我得到的东西(我的机器人的Z坐标):
from pymodbus.client.sync import ModbusTcpClient
from pymodbus.constants import Endian
from pymodbus.payload import BinaryPayloadDecoder
host = '192.168.250.2' # Robot IP address
port = 502 # Modbus port on the robot
client = ModbusTcpClient(host, port)
client.connect()
request = client.read_holding_registers(
address=7053, # The starting address to read from
count=4, # The number of registers to read
unit=1) # The slave unit this request is targeting (slave ID)
#response = client.execute(request)
print(request.registers)
decoder = BinaryPayloadDecoder.fromRegisters(request.registers, Endian.Big, Endian.Little)
print(decoder.decode_32bit_float())
client.close()
输出:
[0, 0, 0, 0]
0.0
这个输出是什么意思?我知道机器人Z坐标是400毫米,但是无论我在请求中使用什么地址,我都得到0。这是调试输出:
DEBUG:pymodbus.transaction:Current transaction state - IDLE
DEBUG:pymodbus.transaction:Running transaction 1
DEBUG:pymodbus.transaction:SEND: 0x0 0x1 0x0 0x0 0x0 0x6 0x1 0x3 0x1b 0x8d 0x0 0x4
DEBUG:pymodbus.client.sync:New Transaction state 'SENDING'
DEBUG:pymodbus.transaction:Changing transaction state from 'SENDING' to 'WAITING FOR REPLY'
DEBUG:pymodbus.transaction:Changing transaction state from 'WAITING FOR REPLY' to 'PROCESSING REPLY'
DEBUG:pymodbus.transaction:RECV: 0x0 0x1 0x0 0x0 0x0 0xb 0x1 0x3 0x8 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0
DEBUG:pymodbus.framer.socket_framer:Processing: 0x0 0x1 0x0 0x0 0x0 0xb 0x1 0x3 0x8 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0
DEBUG:pymodbus.factory:Factory Response[ReadHoldingRegistersResponse: 3]
DEBUG:pymodbus.transaction:Adding transaction 1
DEBUG:pymodbus.transaction:Getting transaction 1
DEBUG:pymodbus.transaction:Changing transaction state from 'PROCESSING REPLY' to 'TRANSACTION_COMPLETE'
DEBUG:pymodbus.payload:[0, 0, 0, 0]
DEBUG:pymodbus.payload:[b'\x00\x00', b'\x00\x00']
我收到的东西在发送,但不完全是在RECV,这不是我所期望的。
https://stackoverflow.com/questions/58840615
复制相似问题