granan granan - 10 months ago 102
Linux Question

How to write on serial port in python that ttyUSB0 will be interpreted commands?

I have raspberry PI B+ with connected Telegesis ZigBee module(ETRX3 USB sticks) via USB. Using commands:

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

the ZigBee module executed ATI command and I can see correct output:

Telegesis ETRX357



The same thing I want to do with python script. I was written python script with code:

#!/usr/bin/env python

# based on tutorials:

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'


except Exception, e:
print "error open serial port: " + str(e)

if ser.isOpen():

ser.flushInput() #flush input buffer, discarding all its contents
ser.flushOutput()#flush output buffer, aborting current output

print("write data: ATI")
numberOfLine = 0

while True:

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

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


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

print "cannot open serial port "

and get results as on the screen


but i want to command be execute by ZigBee module, as like in shell commands. What am I doing wrong?

write on ttyUSB0

Answer Source
  1. you need to append an end-of-line to your write()


  2. you should change the timeout to:

    ser.timeout = None

Otherwise readline() will return after 2 seconds, even if nothing has been read.