from pymodbus.client.sync import ModbusSerialClient#pip3 install pymodbus==2.5.3
client = ModbusSerialClient(method=‘rtu’, port=‘COM7’, baudrate=115200, stopbits=1, bytesize=8, parity=‘N’)
client.connect()
result = client.read_holding_registers(address=0, count=30, unit=1)
if result.isError():
print(“读取保持寄存器失败:”, result)
else:
print(“保持寄存器值:”, result.registers)
register_values = [1, 2, 3, 4, 5] # 要写入的寄存器值列表
starting_address = 90 # 要写入的寄存器起始地址
result = client.write_registers(address=starting_address, values=register_values, unit=1)
if result.isError():
print(“写入寄存器失败:”, result)
else:
print(“寄存器写入成功”)
client.close()