在Python中创建串行对象的麻烦

时间:2014-10-07 11:20:15

标签: python serial-port

我正在编写一个程序,该程序应该使用串行对象与Arduino单元通信。在类的 init 方法中,可以找到这段代码:

    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。什么' S 那个? Arduino单元已插入COM22。

我有另一个我自己没有写过的程序,但是它使用了相同的类库。这个程序有效,但我不明白怎么做。是否存在我错过的串行对象的某种初始化?

2 个答案:

答案 0 :(得分: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

应该正常工作。

答案 1 :(得分:0)

我后来发现错误源于错误定义的模块路径 与班级定义。路径是针对旧版本的 同一个文件。