简体   繁体   English

从Arduino读取时PySerial速度变慢

[英]PySerial slowdown on read from Arduino

I'm attempting to write a handshaking procedure to allow my python program to automatically detect which port the Arduino is on. 我正在尝试编写一个握手过程,以允许我的python程序自动检测Arduino处于哪个端口。 It works, however sometimes it runs extremely slow. 它可以工作,但是有时运行速度非常慢。 Here's the problematic part of my code: 这是我的代码中有问题的部分:

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]))

Essentially I have the Arduino constantly sending the arbitrary number '7' to the serial port. 本质上,我让Arduino不断向串行端口发送任意数字'7'。 The python script scans each port for a 7 until it finds it. python脚本在每个端口上扫描7,直到找到为止。 What's happening is that when it gets to the port that the Arduino is on, the code seemingly pauses executing for about 10 seconds at the arduino = serial.Serial(...) line right underneath the try statement. 发生的事情是,当到达Arduino所在的端口时,代码似乎在try语句下方的arduino = serial.Serial(...)行处暂停执行约10秒钟。 Since it's in a try loop, I know it's not throwing an error because it does eventually make it through. 由于它处于try循环中,因此我知道它不会抛出错误,因为它最终确实可以使它通过。 Is it just having trouble opening the port? 打开端口是否有困难? How can this be fixed? 如何解决? I am on Python 3.4.3 and pySerial 2.7. 我使用的是Python 3.4.3和pySerial 2.7。

I think the issue is more with how arduino does serial ... it waits for a serial connection to open then it does a bunch of setup you can see this with a relatively simple arduino sketch 我认为问题更多在于arduino如何进行串行处理...它等待串行连接打开,然后进行一堆设置,您可以通过一个相对简单的arduino草图看到它

int i;
void setup(){
   i=8;
   Serial.begin(9600);
}
void loop(){
   Serial.print(i);
   Serial.print(",");
   i+=1;
}

and I think that you will always see 8 as the first number when you connect to the port ... I dont have an arduino on hand but I seem to recall seeing this behaviour 而且我认为当您连接到端口时,您总是会看到第一个数字是8 ...我手头没有arduino,但我似乎回想起这种行为

Just to check: Is the baudrate the same for both your Arduino and Python? 只是检查一下:您的Arduino和Python的波特率是否相同? Are there any other programs trying to access the Arduino? 还有其他程序试图访问Arduino吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM