import serial,time,struct import modbus_tk.defines as cst from modbus_tk import modbus_rtu # from modbus_tk.utils import create_master_string def main(): # 打开两个串口 com1 = serial.Serial(port='com2', baudrate=38400, bytesize=8, parity='N', stopbits=1) com2 = serial.Serial(port='com3', baudrate=38400, bytesize=8, parity='N', stopbits=1) # 创建Modbus RTU主机(master) master = modbus_rtu.RtuMaster(com1) master.set_timeout(1.0) master.set_verbose(True) # time.sleep(2) # 读取保持寄存器数据 red = master.execute(1, cst.READ_HOLDING_REGISTERS, 0, 9) print(red) red1 = master.execute(1, cst.READ_HOLDING_REGISTERS, 0, 9)[0] # 这里可以修改需要读取的功能码 print(red1) new = int(red1 * 0.98) print(new) master.execute(1, function_code=cst.WRITE_MULTIPLE_REGISTERS, starting_address=0, output_value=[new]) time.sleep(0.5) red = master.execute(1, cst.READ_HOLDING_REGISTERS, 0, 9) print(red,0) # 读取输入寄存器数据 input_regs = master.execute(1, cst.READ_INPUT_REGISTERS, 0, 9) print(input_regs, 1) # 读取输入线圈数据 input_bits = master.execute(1, cst.READ_COILS, 0, 9) print(input_bits, 2) # 读取输出线圈数据 output_bits = master.execute(1, cst.READ_DISCRETE_INPUTS, 0, 9) print(output_bits, 3)。现在将所有读取数据打包为Modbus RTU消息并写入com2串口。要求打包的Modbus RTU消息格式要跟 master = modbus_rtu.RtuMaster(com1)一样
时间: 2023-11-25 22:08:22 浏览: 158
可以使用modbus_tk.modbus_rtu.master._compute_crc函数计算Modbus RTU消息的校验码,并使用struct.pack()函数将消息打包为字节流。以下是代码示例:
```python
import serial
import time
import struct
import modbus_tk.defines as cst
from modbus_tk import modbus_rtu
def pack_modbus_rtu_msg(address, function_code, starting_address, quantity_of_x, output_value=None):
# 构造Modbus RTU消息
if output_value is not None:
data_len = 2 + 2*len(output_value)
else:
data_len = 2
msg = struct.pack(">BBHH", address, function_code, starting_address, quantity_of_x)
if output_value is not None:
for val in output_value:
msg += struct.pack(">H", val)
# 计算校验码(CRC)
crc = modbus_rtu.master._compute_crc(msg)
msg += struct.pack(">H", crc)
return msg
def main():
# 打开两个串口
com1 = serial.Serial(port='com2', baudrate=38400, bytesize=8, parity='N', stopbits=1)
com2 = serial.Serial(port='com3', baudrate=38400, bytesize=8, parity='N', stopbits=1)
# 创建Modbus RTU主机(master)
master = modbus_rtu.RtuMaster(com1)
master.set_timeout(1.0)
master.set_verbose(True)
# 读取保持寄存器数据
red1 = master.execute(1, cst.READ_HOLDING_REGISTERS, 0, 9)[0]
new = int(red1 * 0.98)
master.execute(1, function_code=cst.WRITE_MULTIPLE_REGISTERS, starting_address=0, output_value=[new])
# 打包Modbus RTU消息并写入com2串口
msg = pack_modbus_rtu_msg(1, cst.READ_HOLDING_REGISTERS, 0, 9)
com2.write(msg)
# 读取输入寄存器数据
input_regs = master.execute(1, cst.READ_INPUT_REGISTERS, 0, 9)
print(input_regs, 1)
# 读取输入线圈数据
input_bits = master.execute(1, cst.READ_COILS, 0, 9)
print(input_bits, 2)
# 读取输出线圈数据
output_bits = master.execute(1, cst.READ_DISCRETE_INPUTS, 0, 9)
print(output_bits, 3)
```
阅读全文