如何在python中向ttyUSB0写入可解析命令的串口?

5 投票
1 回答
26292 浏览
提问于 2025-04-19 18:58

我有一个树莓派 B+,通过 USB 连接了 Telegesis ZigBee 模块(ETRX3 USB 插件)。我使用以下命令:

    debian:~# stty -F /dev/ttyUSB0 -raw ispeed 19200 ospeed 19200
    debian:~# cat < /dev/ttyUSB0 &
    debian:~# echo "ATI" > /dev/ttyUSB0

这个 ZigBee 模块执行了 ATI 命令,我可以看到正确的输出:

   Telegesis ETRX357

   R308C

   OK

我想用 Python 脚本做同样的事情。我写了一个 Python 脚本,代码如下:

    #!/usr/bin/env python

    # based on tutorials:
    #   http://www.roman10.net/serial-port-communication-in-python/
    #   http://www.brettdangerfield.com/post/raspberrypi_tempature_monitor_project/

    import serial, time

    SERIALPORT = "/dev/ttyUSB0"
    BAUDRATE = 19200

    ser = serial.Serial(SERIALPORT, BAUDRATE)

    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 = 0             #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 = 0     #timeout for write

    print 'Starting Up Serial Monitor'

    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

            ser.write("ATI")
            print("write data: ATI")
            time.sleep(0.5)
            numberOfLine = 0

            while True:

                response = ser.readline()
                print("read data: " + response)

                numberOfLine = numberOfLine + 1
                if (numberOfLine >= 5):
                    break

            ser.close()

        except Exception, e:
            print "error communicating...: " + str(e)

    else:
        print "cannot open serial port "

并且得到了和屏幕上一样的结果

    ATI

但是我希望命令能像在命令行中那样被 ZigBee 模块执行。我哪里做错了?

写入 ttyUSB0

1 个回答

2
  1. 你需要在写入内容的后面加一个换行符。

    ser.write("ATI\r\n")

  2. 你应该把超时时间改成:

    ser.timeout = None

否则,readline() 会在2秒后返回,即使没有读取到任何内容。

撰写回答