使用 pyserial 库读写虚拟寄存器modbus slave
import serial
def mod(PORT="com21"):
ser = serial.Serial(PORT, 115200, timeout=1)
ser.isOpen()
ser.write("/xFA/x01/x00/x83/x78".encode())
data = ser.read(69)
print(data)
ser.close()
if __name__ == "__main__":
mod()
但是无论读或写都没有用,但是使用modbus_tk可以。
import serial
import modbus_tk
import modbus_tk.defines as cst
import modbus_tk.modbus_tcp as mt
from modbus_tk import modbus_rtu
def mod(PORT="com21"):
red = []
alarm = ""
try:
# 设定串口为从站
# master = mt.TcpMaster("127.0.0.1", 502)
master = modbus_rtu.RtuMaster(serial.Serial(port=PORT,
baudrate=115200, bytesize=8,parity='N', stopbits=1,xonxoff=0))
master.set_timeout(1)
master.set_verbose(True)
master.execute(1, cst.WRITE_MULTIPLE_REGISTERS, 0, output_value=[0xFA, 0x01, 0x83, 0x00, 0x78])
# 读保持寄存器
red = master.execute(1, cst.READ_HOLDING_REGISTERS, 0, 69) # 这里可以修改需要读取的功能码
print(red)
alarm = "正常"
return list(red), alarm
except Exception as exc:
print(str(exc))
alarm = (str(exc))
return red, alarm ##如果异常就返回[],故障信息
if __name__ == "__main__":
mod()
modbus slave是设置好的,也加了虚拟串口。
想问一下具体原因是什么?这两种库有所区别吗?