[英]Python pySerial read data from arduino breaks when sending “(char)0”
[英]PySerial slowdown on read from Arduino
我正在嘗試編寫一個握手過程,以允許我的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所在的端口時,代碼似乎在try語句下方的arduino = serial.Serial(...)
行處暫停執行約10秒鍾。 由於它處於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,但我似乎回想起這種行為
只是檢查一下:您的Arduino和Python的波特率是否相同? 還有其他程序試圖訪問Arduino嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.