模拟modbus-slave
创建slave
设置
完成
安装pymodbus
pip3 install pymodbus==2.5.3
代码
from pymodbus.client.sync import ModbusTcpClient
from pymodbus.bit_read_message import ReadCoilsResponse
from pymodbus.register_read_message import ReadInputRegistersResponse
from pymodbus.exceptions import ConnectionException # 连接失败,用于异常处理
import time
host = '127.0.0.1'
port = 502
client = ModbusTcpClient(host,port)
print(client.connect())
while client.connect():
print("connected")
# 读取寄存器数据,不能超位读取
result = client.read_holding_registers(0, 10, unit=1)
print(result.registers)
# 修改端口数据
result = client.write_registers(0, [666, 888], unit=1)
print(result)
time.sleep(1)