我想構建一個短代碼,它將測試所有串行COM端口(我在windows上)的回覆。例如,我在COM3上連接了一個Arduino,當它連接時,它會發送一個串行消息。Python:測試串行端口的答案
我希望當我運行python腳本時,它會自動檢測哪個是正確的COM端口。
我有列出所有端口的功能,但是我無法讓它工作來測試它們,並檢測arduino連接到哪個端口。
的Python:
import serial
import time
import _winreg as winreg
import itertools
import datetime
def enumerate_serial_ports():
""" Uses the Win32 registry to return an
iterator of serial (COM) ports
existing on this computer.
"""
path = 'HARDWARE\\DEVICEMAP\\SERIALCOMM'
try:
key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path)
except WindowsError:
raise IterationError
for i in itertools.count():
try:
val = winreg.EnumValue(key, i)
yield str(val[1])
except EnvironmentError:
break
connected = False
for porta in enumerate_serial_ports():
print "TRYING PORT: " + porta
start = datetime.datetime.now()
delta=0
ser = serial.Serial(porta,9600,timeout=0)
if ser.isOpen():
while ser.isOpen() and delta < 1:
delta = (datetime.datetime.now()-start).seconds
r = ser.read()
if r == None:
print "connected!"
Arduino的代碼
void setup(){
// Open serial connection.
Serial.begin(9600);
pinMode(13, OUTPUT);
Serial.write(6);
}
void loop(){
}
謝謝!!