1

我对 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 错误: [连接] 无法连接 [ModbusTcpClient(192.168.250.201:502)]

我想我的代码中一定有问题,或者可能有其他东西阻止我建立连接。有什么建议么?谢谢

4

2 回答 2

0

你有几个小问题:

1)您查询的寄存器地址似乎不正确,请仔细检查您的设备手册,看看您是否读取了正确的地址,很可能您需要查询address=7053

2)您正在读取保持寄存器,但随后您尝试以线圈(位)打印值。检查他们是否真的持有寄存器并使用print(response.registers[0])

于 2019-11-14T05:42:03.110 回答
0

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

于 2019-11-14T10:27:00.460 回答