PySerial 的问题:必须先配置端口才能使用 [英] Issues with PySerial: Port must be configured before it can be used
问题描述
我正在编写代码(在 python 中)以在 Windows 7 上使用 pySerial 库与 Arduino 进行串行通信.但是,我在正确使用端口时遇到了问题.这是我的代码:
I am writing code (in python) to use serial communication with an Arduino, using the pySerial library, on Windows 7. However, I am having issues using the ports correctly. Here is my code:
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() 时,我得到了回溯:
When I have ser.open() in the code, I get the traceback:
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() 注释掉时,我得到了回溯:
When I have ser.open() commented out, I get the traceback:
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,这可能是问题的一部分吗?
I am new to serial connections, and do not understand what is going wrong. By the examples I have found of code online, this code should work. Is anyone able to see where I am going wrong? A lot of the examples I have seen are for Apple or Linux, which use a different convention for naming USB's, could that be part of the problem?
在此先谢谢你!!
推荐答案
我猜第二个 ser = serial.Serial()
会覆盖你在前几行.您正在用一个新的串行端口对象替换它,该对象是在没有给它任何参数的情况下创建的.尝试注释掉该行.
I guess that with the second ser = serial.Serial()
, you are overwriting the serial port object that you created in the first few lines. You are replacing it with a new serial port object, which was created without giving it any parameters. Try commenting out that line.
这篇关于PySerial 的问题:必须先配置端口才能使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!