2013-04-10 163 views
1

當我從我的PC上拔下USB/Arduino時,從中刪除它的Python腳本崩潰。在Python中存活一個臨時COM端口斷開連接

#The connection to the Arduino 
ser = serial.Serial('COM19',9600) 

#Not connected to Arduino before connection is made 
connected = False 

#Loop until the Arduino is connected 
while not connected: 
    serin = ser.read() 
    connected = True 

#Debug Arduino connection 
if connected == True: 
    pprint('connected to arduino') 

我曾嘗試使用TRY/EXCEPT,以確保重新連接的連接時,但是當Arduino的再次插入,它不會承認的COM端口,直到計算機已被重置。

from pprint import pprint 
import time 
import serial 

while True: 
    #The connection to the Arduino 
    try: 
     ardResponse = serial.Serial('COM19',9600) 
    except IOError: 
     connected = False 
     pprint('Arduino not connected to COM3') 
     time.sleep(10) 
    continue 
    serin = ser.read() 
    connected = True 
    pprint('Connected to Arduino') 
    ser.write('1') 
    while ser.read() == '1': 
     ser.read() 
    pprint ('Arduino has finished being flashed') 

    ser.close() 
    pprint('Connection closed') 

    time.sleep(5) 

這是因爲COM端口保持打開狀態,所以腳本無法重用它?有沒有辦法避免這個問題?

回答

0

嘗試在除了: 之外的地方執行ser.close(),然後提示用戶修復它,然後在再次嘗試ser.open()之前按Enter鍵。