Python串行-尝试使用未打开的端口

hil*_*llz 5 python pyserial

我仍然是python的新手,所以请多多包涵,所以我试图用编写脚本,python2-pyserial但是我一直收到错误消息。Attempting to use a port that is not open这是脚本:

#!/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 ")
Run Code Online (Sandbox Code Playgroud)

我尝试使用运行脚本,sudo python2 ser但是仍然有相同的错误。我如何解决它 ?

ale*_*ocb 2

您的代码的第一部分是错误的,您为 ser 做出了错误的归因。尝试以下方法:

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
)
Run Code Online (Sandbox Code Playgroud)

在我的环境中,此后端口已经打开,但如果没有打开,您可以尝试打开它:

ser.open()
ser.isOpen()
Run Code Online (Sandbox Code Playgroud)

并且您必须确保这不是您电脑上的虚拟端口,如果是,则必须更改此设置:

ser.rtscts = False  #disable hardware (RTS/CTS) flow control
ser.dsrdtr = False  #disable hardware (DSR/DTR) flow control
Run Code Online (Sandbox Code Playgroud)

为了这:

ser.rtscts = True
ser.dsrdtr = True
Run Code Online (Sandbox Code Playgroud)

查看此问题以获取更多信息