2016-05-18 56 views
2

我仍然是新的python所以請忍受我,所以我想寫一個腳本python2-pyserial,但我不斷收到錯誤Attempting to use a port that is not open這裏的腳本:Python串行 - 試圖使用一個未打開的端口

#!/usr/bin/python 

import serial, time 
#initialization and open the port 
#possible timeout values: 
# 1. None: wait forever, block call 
# 2. 0: non-blocking mode, return immediately 
# 3. x, x is bigger than 0, float allowed, timeout block call 
ser = serial.Serial() 
ser.port = "/dev/ttyUSB2" 
ser.baudrate = 115200 
ser.bytesize = serial.EIGHTBITS #number of bits per bytes 
ser.parity = serial.PARITY_NONE #set parity check: no parity 
ser.stopbits = serial.STOPBITS_ONE #number of stop bits 
#ser.timeout = None   #block read 
ser.timeout = 1   #non-block read 
#ser.timeout = 2    #timeout block read 
ser.xonxoff = False  #disable software flow control 
ser.rtscts = False  #disable hardware (RTS/CTS) flow control 
ser.dsrdtr = False  #disable hardware (DSR/DTR) flow control 
ser.writeTimeout = 2  #timeout for write 
try: 
    ser.open() 
    print ("Port has been opened") 
except Exception, e: 
    print ("error open serial port: ") + str(e) 
    exit() 

if ser.isOpen(): 
    try: 
     ser.flushInput() #flush input buffer, discarding all its contents 
     ser.flushOutput() 
     ser.write("ATI") 
     print("write data: ATI") 
     time.sleep(1) #give the serial port sometime to receive the data 
     numOfLines = 0 
     while True: 
      response = ser.readline() 
      print("read data: " + response) 
      numOfLines = numOfLines + 1 
      if (numOfLines >= 5): 
       break 
       #pass 
      ser.close() 
    except Exception, e1: 
     print ("error communicating...: ") + str(e1) 
else: 
    print ("cannot open serial port ") 

我試過用sudo python2 ser運行腳本,但我仍然有同樣的錯誤。我如何解決它 ?

+0

您是否嘗試過使用下面的代碼段? –

回答

1

你的代碼的第一部分是錯誤的,你正在爲服務做出錯誤的歸因。請嘗試以下方法:

ser = serial.Serial(
port = "/dev/ttyUSB2", 
baudrate = 115200, 
bytesize = serial.EIGHTBITS, 
parity = serial.PARITY_NONE, 
stopbits = serial.STOPBITS_ONE, 
timeout = 1, 
xonxoff = False, 
rtscts = False, 
dsrdtr = False, 
writeTimeout = 2 
) 

在我的環境,端口已經在這之後開放的,但如果它不是你可以嘗試打開它:

ser.open() 
ser.isOpen() 

而且你必須確保這是不是您的PC上的虛擬端口如果是這樣,你必須改變這一點:

ser.rtscts = False #disable hardware (RTS/CTS) flow control 
ser.dsrdtr = False #disable hardware (DSR/DTR) flow control 

對於這一點:

ser.rtscts = True 
ser.dsrdtr = True 

查看詳情issue瞭解更多信息