我按照上面的建议修复了我的代码,我还添加了 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']
我得到了 SEND 中的东西,但不是 RECV 中的东西,这不是我所期望的。