我正在尝试编写一个握手程序,以允许我的 python 程序自动检测 Arduino 所在的端口。它可以工作,但有时运行速度非常慢。这是我的代码中有问题的部分:
import serial, serial.tools.list_ports, time
portList = list(serial.toools.list_ports.comports())
conn = 0
while conn == 0:
for port in portList:
print(port[0])
try:
arduino = serial.Serial(port[0], 4800, timeout=.1)
time.sleep(.2)
sig = arduino.read()
signum = int.from_bytes(sig, byteorder='little')
if signum == 7:
global comport
comport = port[0]
conn = 1
break
except:
print('Could not read from ' + str(port[0]))
本质上,我让 Arduino 不断向串行端口发送任意数字“7”。 python 脚本扫描每个端口是否有 7,直到找到为止。发生的情况是,当它到达 Arduino 所在的端口时,代码似乎在 arduino = serial.Serial(...)
处暂停执行大约 10 秒。 try 语句正下方的一行。因为它处于 try 循环中,所以我知道它不会抛出错误,因为它最终会成功。只是打开端口时遇到问题吗?如何解决这个问题?我使用的是 Python 3.4.3 和 pySerial 2.7。
最佳答案
我认为问题更多在于arduino如何进行串行...它等待串行连接打开,然后进行一系列设置,您可以使用相对简单的arduino草图看到这一点
int i;
void setup(){
i=8;
Serial.begin(9600);
}
void loop(){
Serial.print(i);
Serial.print(",");
i+=1;
}
我认为当您连接到端口时,您总是会看到 8 作为第一个数字...我手头没有 arduino,但我似乎记得看到过这种行为
关于python - PySerial 从 Arduino 读取时速度变慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31325976/