pySerial buffer won't flush

Robert Jordan picture Robert Jordan · Sep 1, 2011 · Viewed 67.7k times · Source

I'm having a problem with serial IO under both Windows and Linux using pySerial. With this code the device never receives the command and the read times out:

import serial
ser = serial.Serial('/dev/ttyUSB0',9600,timeout=5)
ser.write("get")
ser.flush()
print ser.read()

This code times out the first time through, but subsequent iterations succeed:

import serial
ser = serial.Serial('/dev/ttyUSB0',9600,timeout=5)
while True:
    ser.write("get")
    ser.flush()
    print ser.read()

Can anyone tell what's going on? I tried to add a call to sync() but it wouldn't take a serial object as it's argument.

Thanks, Robert

Answer

beebek picture beebek · Oct 15, 2012

Put some delay in between write and read e.g.

import serial
ser = serial.Serial('/dev/ttyUSB0',9600,timeout=5)
ser.flushInput()
ser.flushOutput()
ser.write("get") 

# sleep(1) for 100 millisecond delay
# 100ms dely
sleep(.1)
print ser.read()