当我从我的 PC 上拔下 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 端口保持打开状态,因此脚本无法重用它吗?有没有办法避免这个问题?