2014-10-07 49 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

我后来发现这个错误源于错误定义的类路径模块 的路径。该路径被导向到相同文件的旧版本 。