import serial import modbus_tk.defines as cst from modbus_tk import modbus_rtu import struct # 打开两个串口 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) # 读取保持寄存器数据 red = master.execute(1, cst.READ_HOLDING_REGISTERS, 0, 9) print(red) # 将字节数组划分为若干个长度为4的子数组 # def hex_f(a,b): # # g1=b # # z=a+g1#高低16位组合 # # z1=hex(z)[2:]#取0x后边的部分 # # # print(z1) # # return struct.unpack('!f', z1.decode('hex'))[0]#返回浮点数 # # e = hex_f(red[0],red[1]) # # print(e) red1 = master.execute(1, cst.READ_HOLDING_REGISTERS, 0, 9)[0] # 这里可以修改需要读取的功能码 print(red1) new = int(red1 * 0.8) print(new) red =master.execute(1, function_code=cst.WRITE_MULTIPLE_REGISTERS, starting_address=0, output_value=[new]) # 读取输入寄存器数据 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串口 data = red + input_regs + input_bits + output_bits com2.write(master._do_crc(data)) # 关闭串口 com1.close() com2.close()AttributeError: 'RtuMaster' object has no attribute '_do_crc'咋修改不报错
时间: 2024-02-04 13:03:46 浏览: 138
mpc85xx_edac.rar_V2
您可以将最后一行代码修改为使用modbus_tk.utils.create_master_string()函数将数据打包为Modbus RTU消息,并通过com2串口发送出去。修改后的代码如下:
```
import serial
import modbus_tk.defines as cst
from modbus_tk import modbus_rtu
from modbus_tk.utils import create_master_string
# 打开两个串口
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)
# 读取保持寄存器数据
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.8)
print(new)
red = master.execute(1, function_code=cst.WRITE_MULTIPLE_REGISTERS, starting_address=0, output_value=[new])
# 读取输入寄存器数据
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串口
data = red + input_regs + input_bits + output_bits
com2.write(create_master_string(data, 1))
# 关闭串口
com1.close()
com2.close()
```
这样就不会出现之前的错误了。
阅读全文