我很难获得pyserial和一个玩得很好虚拟端口。我知道这是其他一些人写过的领域,但我在这些答案中找不到任何可以解决我的问题的内容。如果我只是太笨了,请原谅我,解决方案在其他地方已经存在。
这就是我想要实现的目标:我想设置一个虚拟端口,我可以在一个 .py 文件中写入数据,然后可以从中读取另一个 .py 文件中的数据。这是为了开发和测试的目的;我并不总是能够访问构建当前项目的设备。
到目前为止,这是我的代码:
虚拟串行.py
import os, pty, serial, time
master, slave = pty.openpty()
m_name = os.ttyname(master)
s_name = os.ttyname(slave)
# This tells us which ports "openpty" has happened to choose.
print("master: "+m_name)
print("slave: "+s_name)
ser = serial.Serial(s_name, 9600)
message = "Hello, world!"
encoded = message.encode("ascii")
while True:
ser.write(encoded)
time.sleep(1)
读者.py
import serial, time
# The port will change, depending on what port "openpty" (in the other file)
# happens to choose.
ser = serial.Serial("/dev/pts/1", 9600)
while True:
time.sleep(1)
incoming_bytes = ser.inWaiting()
# This print statement gives us an idea of what's going on.
print(incoming_bytes)
if incoming_bytes != 0:
data = ser.read(incoming_bytes)
print(data)
目前,dummy_serial.py 似乎运行正常。然而,reader.py 只是一直说没有字节等待读取,因此不读取任何数据。
我想要什么:
- 原因的解释
ser.inWaiting()
不断返回 0,并且有一个解决方案使得ser.read(x)
实际上吐出“你好,世界!”
-
Or解释为什么我想做的事情从根本上来说是愚蠢的,也是创建可写/可读虚拟端口的更好方法。