在Python中幸存临时COM端口断开连接

时间:2013-04-10 10:31:30

标签: windows-7 python-2.7 serial-port arduino

当我从我的电脑上拔下USB / Arduino时,删除它的Python脚本崩溃了。

#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端口保持打开状态,所以脚本无法重用吗?有没有办法避免这个问题?

1 个答案:

答案 0 :(得分:0)

尝试在except:block中执行ser.close() 然后提示用户修复它,并在再次尝试ser.open()之前按Enter键。