如何在python的串行端口上编写ttyUSB0将被解释为命令?

如何在python的串行端口上编写ttyUSB0将被解释为命令?,python,linux,serial-port,raspberry-pi,zigbee,Python,Linux,Serial Port,Raspberry Pi,Zigbee,我有树莓皮B+与通过USB连接的Telegesis ZigBee模块(ETRX3 U盘)。使用命令: debian:~# stty -F /dev/ttyUSB0 -raw ispeed 19200 ospeed 19200 debian:~# cat < /dev/ttyUSB0 & debian:~# echo "ATI" > /dev/ttyUSB0 我想用python脚本做同样的事情。我是用以下代码编写python脚本的: #!/us

我有树莓皮B+与通过USB连接的Telegesis ZigBee模块(ETRX3 U盘)。使用命令:

    debian:~# stty -F /dev/ttyUSB0 -raw ispeed 19200 ospeed 19200
    debian:~# cat < /dev/ttyUSB0 &
    debian:~# echo "ATI" > /dev/ttyUSB0
我想用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模块执行,就像shell命令一样。我做错了什么

  • 您需要在write()中追加一行末尾

    ser.write(“ATI\r\n”)

  • 您应该将超时更改为:

    ser.timeout=None

  • 否则,readline()将在2秒后返回,即使未读取任何内容

        ATI