6,116
社区成员
发帖
与我相关
我的任务
分享
python的modbus-tcp协议采集仪表数据报错。不知错误在哪。
from pymodbus.client.sync import ModbusTcpClient
# 电力仪表的IP地址和端口
METER_IP = "192.168.16.100"
METER_PORT = 502
# 创建Modbus TCP客户端实例
client = ModbusTcpClient(METER_IP, port=METER_PORT)
if client.connect():
print("成功连接到电力仪表")
try:
# 读取保持寄存器数据,寄存器地址为896,读取1个寄存器
address = 896 # 寄存器地址
count = 1 # 要读取的寄存器数量
unit_identifier = 1 # 单元标识符,需根据仪表实际配置来设置
# 使用功能码03读取保持寄存器
result = client.read_holding_registers(address, count, unit=unit_identifier)
# 检查结果是否有效
if not result.isError():
registers = result.registers
print(f"读取到的保持寄存器数据: {registers}")
else:
print(f"读取保持寄存器数据出现错误: {result}")
except Exception as e:
print(f"读取保持寄存器数据时出现异常: {e}")
finally:
# 关闭连接
client.close()
print("已关闭与电力仪表的连接")
else:
print("无法连接到电力仪表")
pymodbus用的是2.5.3版本。开始用的最新版本,读取不同,论坛查阅之后,根据其他博主的解决方案,降低版本后,可以使用,运行程序之后,显示通讯成功,但是读取不到数据。报错内容如下:
Modbus Error: [Input/Output] Modbus Error: [Invalid Message] No response received, expected at least 8 bytes (0 received)