微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Python serial – 尝试使用未打开的端口

我仍然是 python中的新手,所以请耐心等待,所以我正在尝试用python2-pyserial写一个脚本但是我一直在收到错误尝试使用一个未打开的端口这是脚本:

#!/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运行脚本,但我仍然有同样的错误.我如何解决它 ?

解决方法

你的代码的第一部分是错误的,你正在为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
)

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

ser.open()
ser.isopen()

而且你必须确保这不是你电脑上的虚拟端口,如果是,你将不得不改变这个:

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了解更多信息

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐