使用pySerial包的完整示例

104

请问有没有人能够展示一个完整的Python样例代码,使用PySerial,我已经拥有这个包并且想知道如何发送AT指令并读取其返回值!

4个回答

101

博客文章 Python中的串行RS232连接

import time
import serial

# configure the serial connections (the parameters differs on the device you are connecting to)
ser = serial.Serial(
    port='/dev/ttyUSB1',
    baudrate=9600,
    parity=serial.PARITY_ODD,
    stopbits=serial.STOPBITS_TWO,
    bytesize=serial.SEVENBITS
)

ser.isOpen()

print 'Enter your commands below.\r\nInsert "exit" to leave the application.'

input=1
while 1 :
    # get keyboard input
    input = raw_input(">> ")
        # Python 3 users
        # input = input(">> ")
    if input == 'exit':
        ser.close()
        exit()
    else:
        # send the character to the device
        # (note that I happend a \r\n carriage return and line feed to the characters - this is requested by my device)
        ser.write(input + '\r\n')
        out = ''
        # let's wait one second before reading output (let's give device time to answer)
        time.sleep(1)
        while ser.inWaiting() > 0:
            out += ser.read(1)
            
        if out != '':
            print ">>" + out

11
运行此代码时,我收到了一个错误serial.serialutil.SerialException: Port is already open。我不确定,但我认为当串口被显式定义为ser时,它会自动打开。注释掉ser.open()这一行后,代码可以正常运行。 - user3817250
这个注释是救星。 - saurabh agarwal
1
@user3817250:或者只需在ser.open()周围添加一个if-case。 - arc_lupus
1
顺便提一下,仅有ser.isopen()本身并没有任何意义。当然,在尝试打开之前,您可以在条件语句中使用isopen(r)来检查它是否已经打开。如果是这样,可能表示您的程序已在其他地方运行。然后使用一些Python技巧来终止其他进程,然后重试打开。https://dev59.com/U2025IYBdhLWcg3wKSiP - SDsolar
1
你好,代码写得很棒!我有一个问题,如果使用Python 3,你会如何更改呢? - Luis Jose

50
import serial
ser = serial.Serial(0)  # open first serial port
print ser.portstr       # check which port was really used
ser.write("hello")      # write a string
ser.close()             # close port

请使用https://pythonhosted.org/pyserial/获取更多示例。


29

http://web.archive.org/web/20131107050923/http://www.roman10.net/serial-port-communication-in-python/comment-page-1/

#!/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/ttyUSB0"
ser.port = "/dev/ttyUSB7"
#ser.port = "/dev/ttyS2"
ser.baudrate = 9600
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()
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()#flush output buffer, aborting current output 
                 #and discard all that is in buffer

        #write data
        ser.write("AT+CSQ")
        print("write data: AT+CSQ")

       time.sleep(0.5)  #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

        ser.close()
    except Exception, e1:
        print "error communicating...: " + str(e1)

else:
    print "cannot open serial port "

2

我没有使用过pyserial,但根据API文档显示它似乎是一个非常好的接口。你可能需要仔细检查设备/无线电等的AT命令规范。

具体来说,有些要求在AT命令之前和/或之后保持一段静默时间才能进入命令模式。我曾经遇到过一些不喜欢在没有延迟的情况下读取响应的设备。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接