Python serial.readline() not blocking
10,085
readline()
uses the same timeout value you passed to serial.Serial()
.
If you want readline to be blocking, just delete the timeout argument, the default value is None
.
You could also set it to None
before calling readline()
, if you want to have a timeout for openening the device:
import serial
try:
device = serial.Serial("/dev/ttyUSB0", 9600, timeout=0.5)
except:
#Exception handeling
device.flushInput()
device.write("command")
device.timeout=None
response = device.readline()
print response
Author by
Rachie
Updated on June 04, 2022Comments
-
Rachie almost 2 years
I'm trying to use hardware serial port devices with Python, but I'm having timing issues. If I send an interrogation command to the device, it should respond with data. If I try to read the incoming data too quickly, it receives nothing.
import serial device = serial.Serial("/dev/ttyUSB0", 9600, timeout=0) device.flushInput() device.write("command") response = device.readline() print response ''
The
readline()
command isn't blocking and waiting for a new line as it should. Is there a simple workaround?-
Paul Rooney over 7 yearsDon't know if it helps but the docs show a
flush
call between thewrite
andreadline
. Also its difficult to understand whatserial
actually is and how its been configured. Can you post a more complete code example that someone could actually run and see the problem -
paxdiablo over 7 yearsWhat is your timeout value set to?
-
Rachie over 7 yearsI expanded the example. I added the
flush()
, but it didn't help.
-