[英]Python PySerial, How to Open Serial Ports?
I'm trying to run this example program from the PySerial Documentation for opening serial ports. 我正在尝试从PySerial文档中运行此示例程序以打开串行端口。 Source: http://pyserial.sourceforge.net/shortintro.html I tried running the code in both python version 2.7 and 3.4 but still get same error. 来源: http : //pyserial.sourceforge.net/shortintro.html我尝试在python版本2.7和3.4中运行代码,但仍然遇到相同的错误。
>>> import serial
>>> ser = serial.Serial(0) # open first serial port
>>> print ser.name # check which port was really used
>>> ser.write("hello") # write a string
>>> ser.close() # close port
I get the following error after running the second line of code: 运行第二行代码后,出现以下错误:
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
ser = serial.Serial(0)
File "C:\Python27\lib\site-packages\serial\serialwin32.py", line 38, in __init__
SerialBase.__init__(self, *args, **kwargs)
File "C:\Python27\lib\site-packages\serial\serialutil.py", line 282, in __init__
self.open()
File "C:\Python27\lib\site-packages\serial\serialwin32.py", line 66, in open
raise SerialException("could not open port %r: %r" % (self.portstr, ctypes.WinError()))
SerialException: could not open port 'COM1': WindowsError(2, 'The system cannot find the file specified.')
It sounds like COM1 is not available (it doesn't exist or it's already being used). 听起来COM1不可用(它不存在或已经被使用)。 I made this little scripts for listing available COM ports. 我制作了这个小脚本来列出可用的COM端口。
import serial
ser=serial.Serial()
for ns in xrange(101):
try:
ser.port=ns
ser.open()
print "COM"+str(ns+1)+" available"
ser.close()
except serial.SerialException:
print "COM"+str(ns+1)+" NOT available"
Remember that the COM port number is the number you pass to serial +1 (serial.Serial(0) opens COM1, serial.Serial(1) opens COM2, etc.) 请记住,COM端口号是您传递给串行+1的数字(serial.Serial(0)打开COM1,serial.Serial(1)打开COM2,依此类推)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.