PySerial的问题:必须先配置端口才能使用它

时间:2015-05-14 20:23:29

标签: python usb pyserial

我正在编写代码(在python中),在Windows 7上使用pySerial库与Arduino进行串行通信。但是,我在使用端口时遇到问题。这是我的代码:

import serial 

#sets the connection parameters, relook at when know more
ser = serial.Serial(
port ='COM4', 
baudrate = 9600, 
parity = serial.PARITY_ODD, 
stopbits = serial.STOPBITS_TWO, 
bytesize = serial.EIGHTBITS
)

ser = serial.Serial() 

ser.open()      #opens port 
ser.isOpen()    #returns true?

handStateList = [0]*3   #array to hold motor values in 
leftMotorState = 0
rightMotorState = 0
wristBend = 0

while True:
    #need to create options to send to arduino

    if wristBend == 'Left':
        leftMotorState = 127
        rightMotorState = 0
    elif wristBend == 'Right':
        leftMotorState = 0
        rightMotorState = 127
    else:
        leftMotorState = 0
        rightMotorState = 0

    #handStateList = ser.readline()

    handStateList[0] = leftMotorState
    handStateList[1] = rightMotorState
    handStateList[2] = '\n'


    ser.write(handStateList)

当我在代码中有ser.open()时,我得到了回溯:

File "vibMotorTest1.py" line 16, in <module> 
ser.open()
File"C:\Python34\lib\site-packages\serial\serialwin32.py", line 44 in open
raise SerialException("Port must be configured before it can be used.")
serial.serialutil.SerialEception: Port must be configured before it can be used

当我将ser.open()注释掉时,我得到了追溯:

File "vibMotorTest1.py", line 44, in <module>
  ser.write(HandStateList)
File"C:\Python34\lib\site-packages\serial\serialwin32.py", line 279, in write 
  if not self.hComPort: raise portNotOpenError
serial.serialutil.SerialException: Attempting to use a port that is not open

我是串口连接新手,不明白出了什么问题。通过我在网上找到代码的例子,这段代码应该可行。有人能够看到我错在哪里吗?我见过很多针对Apple或Linux的例子,它们使用不同的惯例来命名USB,这可能是问题的一部分吗?

提前非常感谢!!

1 个答案:

答案 0 :(得分:1)

我想,对于第二个ser = serial.Serial(),您将覆盖在前几行中创建的串行端口对象。您正在使用新的串行端口对象替换它,该对象是在没有给出任何参数的情况下创建的。尝试评论该行。