2017-09-25 85 views
1

我有一個python程序,我正在使用它來與一個微控制器交談。它打開了COM端口是這樣的:爲什麼我的COM端口很忙?

def STM32_connect(): 
    ports = list(serial.tools.list_ports.comports()) 
    for p in ports: 
     if "STM32" in p.description: 
      connection = serial.Serial(p.device, timeout = .01) 
      return(connection) 
    print("ERROR: No STM32 Device Found") 
    sys.exit() 

serial_connection = STM32_connect() 

然後做了一堆東西,發送和接收數據,直到我關閉程序像這樣用鍵盤interput:

except: 
    print("\n Program Interrupted...") 
finally: 
    print("\n Closing Serial Port\n") 
    serial_connection.close() 

這一切工作正常。我的問題是,當python腳本通過斷開USB電纜或關閉電路板而無法正常工作時,我無法再連接到任何COM端口上的micro。我收到此錯誤:

Traceback (most recent call last): 
    File "/home/---/.local/lib/python3.5/site-packages/serial/serialposix.py", line 265, in open 
    self.fd = os.open(self.portstr, os.O_RDWR | os.O_NOCTTY | os.O_NONBLOCK) 
OSError: [Errno 16] Device or resource busy: '/dev/ttyACM2' 

During handling of the above exception, another exception occurred: 

    Traceback (most recent call last): 
     File "flextester.py", line 1, in <module> 
     from flex_usb_class import * 
     File "/home/---/Code/RobotFlexTester/flex_usb_class.py", line 30, in <module> 
     serial_connection = STM32_connect() 
     File "/home/---/Code/RobotFlexTester/flex_usb_class.py", line 25, in STM32_connect 
     connection = serial.Serial(p.device, timeout = .01) 
     File "/home/---/.local/lib/python3.5/site-packages/serial/serialutil.py", line 240, in __init__ 
     self.open() 
     File "/home/janey/.local/lib/python3.5/site-packages/serial/serialposix.py", line 268, in open 
     raise SerialException(msg.errno, "could not open port {}: {}".format(self._port, msg)) 
    serial.serialutil.SerialException: [Errno 16] could not open port /dev/ttyACM2: [Errno 16] Device or resource busy: '/dev/ttyACM2' 

我可以改變COM端口和我收到完全相同的錯誤在不同ttyACM端口。但是如果我嘗試運行不同的python腳本,我可以連接到同一端口上的相同設備。問題似乎以某種方式被鎖定到初始測試腳本,但ps -a未顯示它仍然在運行。大約30秒後 - 1分鐘後,問題就消失了。

回答

1

延時30s到1min是由於RS232協議的內部原因造成的。當斷開USB電纜和連接被終止時,請參閱setserial命令(http://manpages.ubuntu.com/manpages/zesty/man8/setserial.8.html)中的closing_wait選項(默認30秒),該協議將等待closing_wait選項中指定的時間,直到關閉端口/會話。 session_lockout禁止將第二個工藝附加到開放端口...