【问题标题】:Surviving a temporary COM port disconnection in Python在 Python 中幸存的临时 COM 端口断开连接
【发布时间】:2013-04-10 10:31:30
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-07
      相关资源
      最近更新 更多