2014-10-07 28 views
0

我正在編寫一個程序,該程序應該使用串行對象與Arduino單元進行通信。在類的初始化 - 方法這段代碼可以發現:在Python中創建串行對象的麻煩

try: 
     self.rotor = serial.Serial(port = "COM22", baudrate=115200, timeout = 0.1, writeTimeout = 1) 
    except serial.SerialException, e: 
     print "Error when connecting to collimator: ", e 

當我運行它,我得到這個錯誤信息:

SerialException: could not open port 'COM1': WindowsError(2, 'The system cannot find the file specified.') 

我問電腦打開COM22,並回應它無法打開COM1。什麼是 那? Arduino單元插入COM22。

我有另一個程序,我沒有自己寫,但它使用相同的類庫。這個程序有效,但我不明白。是否有某種我錯過的串行對象的初始化?

+0

該錯誤可能發生在別的地方。如果錯誤發生在代碼中,您的try catch仍然會捕獲該錯誤。 – HashSplat 2014-10-07 11:58:27

回答

2

從在PySerial SVN主幹(http://svn.code.sf.net/p/pyserial/code/trunk/pyserial/serial/serialwin32.py)的Win32Serial對象的源代碼:

def open(self): 
    """\ 
    Open port with current settings. This may throw a SerialException 
    if the port cannot be opened. 
    """ 
    if self._port is None: 
     raise SerialException("Port must be configured before it can be used.") 
    if self._isOpen: 
     raise SerialException("Port is already open.") 
    # the "\\.\COMx" format is required for devices other than COM1-COM8 
    # not all versions of windows seem to support this properly 
    # so that the first few ports are used with the DOS device name 
    port = self.portstr 

因此改變你的代碼:

try: 
     self.rotor = serial.Serial(port = r"\\.\COM22", baudrate=115200, timeout = 0.1, writeTimeout = 1) 
    except serial.SerialException, e: 
     print "Error when connecting to collimator: ", e 

應能正常工作。

0

我後來發現這個錯誤源於錯誤定義的類路徑模塊 的路徑。該路徑被導向到相同文件的舊版本 。