1.创建虚拟串口
使用python代码,创建两个虚拟串口(串口1和串口2),写串口1时串口2将收到消息,写串口2时串口1将收到消息。
import pty
import os
import select
def mkpty():
#
master1, slave = pty.openpty()
slaveName1 = os.ttyname(slave)
master2, slave = pty.openpty()
slaveName2 = os.ttyname(slave)
print('/nslave device names: ', slaveName1, slaveName2)
return master1, master2
if __name__ == "__main__":
master1, master2 = mkpty()
while True:
rl, wl, el = select.select([master1,master2], [], [], 1)
for master in rl:
data = os.read(master, 128)
if master==master1:
print("read %d data:" % len(data)
)
print(data
)
#os.write(master2, data)
else:
print("to write %d data:" % len(data)
)
print(data.strip()
)
os.write(master1, data.strip())
在命令窗口1中运行,结果如下。
2.向虚拟串口2写入数据
新建命令窗口2,执行如下命令,向串口2写数据
cd /dev/pts
echo 'test_message' > 2
3.虚拟串口1读取数据
【开始菜单】【编程】【Thonny Python IDE】,执行如下代码,从串口1读数据(非阻塞)
import serial
ser = serial.Serial('/dev/pts/1',115200,parity=serial.PARITY_NONE)
if ser.isOpen()==0:
ser.open()
ser.write('serial turn on'.encode())
while 1:
# 获得接收缓冲区字符
size = ser.inWaiting()
if size !=0:
# 读取内容并回显
response = ser.read(size)
print(response)