2015-01-02 135 views
2

我想從PySerial文檔中運行這個示例程序來打開串口。來源:http://pyserial.sourceforge.net/shortintro.html 我試着在Python 2.7和3.4版本中運行代碼,但仍然得到相同的錯誤。Python PySerial,如何打開串行端口?

>>> 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 

我收到以下錯誤運行代碼的第二行之後:

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.') 
+0

試過數使用另一個程序,如超級終端或附帶的MiniTerm連接到串行端口,以確保它們可用?你在使用什麼操作系統? – skrrgwasme

+2

您的系統實際上是否有COM1端口? –

+0

我如何知道我的系統是否有COM1端口? – George

回答

0

這聽起來像COM1不可用(它不存在,或者它已被使用)。 我做了這個小腳本列出可用的COM端口。

import serial 
ser=serial.Serial() 
ns=0 
while True : 
    try: 
     ser.port=ns 
     ser.open() 
     print "COM"+str(ns+1)+" avaible" 
     ser.close() 

    except serial.SerialException: 
     print "COM"+str(ns+1)+" NOT avaible" 
    ns=ns+1 
    if(ns>100): 
     break 

記住COM端口號是你通過串行你+1(serial.Serial(0)打開COM1,serial.Serial(1)打開COM2等)

+1

通過使用「for xrange(101):」in「while True:」中的ns,可以使循環更加pythonic,並消除循環中所需的手動初始化,遞增和測試/中斷行。 – RufusVS