我必须从我的三菱 Melservo J4 读取 1 个参数,更具体地说,它是 MR-J4-40A-RJ。 我实际上可以从一个名为 QModMaster 的程序读取参数。 连接的设置如下: 在此输入图片描述 在此输入图片描述
总结为:
我的Python代码是这样的,并且不工作,因为它在获取一些数据之前超时:
from pymodbus.client import ModbusSerialClient as ModbusClient
from pymodbus.payload import BinaryPayloadDecoder
from pymodbus.constants import Endian
from pymodbus.exceptions import ModbusIOException
# Create Modbus client instance
client = ModbusClient(
method='rtu',
port='COM7',
baudrate=115200,
parity='N',
stopbits=2,
bytesize=8,
timeout=1,
rtscts=True
)
# Connect to the serial port
connection = client.connect()
if connection:
print("Connected to the Modbus server")
else:
print("Failed to connect to the Modbus server")
# Register address and number of registers to read
register_address = 0x2103 # 2103h in hexadecimal
num_registers = 2
# Reading the registers
try:
response = client.read_holding_registers(register_address, num_registers, unit=1)
if not isinstance(response, ModbusIOException):
# Decode the response
decoder = BinaryPayloadDecoder.fromRegisters(response.registers, byteorder=Endian.Big, wordorder=Endian.Big)
parameter_value = decoder.decode_32bit_int()
print(f"Parameter PC03 value: {parameter_value}")
else:
print(f"Error reading registers: {response}")
except Exception as e:
print(f"Exception: {e}")
# Close the client
client.close()
我从“响应”中收到此错误:
Error reading registers: Modbus Error: [Input/Output] Modbus Error: [Invalid Message] No response received, expected at least 4 bytes (0 received)
从文档来看,这是 2103h 参数: 在此输入图片描述
我希望我说得很清楚,如有任何问题,我会提供更多信息。
谢谢。
我尝试了我的Python代码,我期望至少有一些字节,但我得到了0字节。
哦,我明白了,希望这能帮助那些需要通过串口与像我这样的设备进行通信的人。
问题是我设置错误:
response = client.read_holding_registers(register_address, num_registers, unit=1)
意思是:
response = client.read_holding_registers(start_address, count, slave=1)
所以问题是你必须设置“slave”而不是“unit”
希望这会对示例代码有所帮助。