2

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?

Rachie
  • 433
  • 1
  • 6
  • 17
  • 1
    Don't know if it helps but the [docs](http://pyserial.readthedocs.io/en/latest/shortintro.html#readline) show a `flush` call between the `write` and `readline`. Also its difficult to understand what `serial` actually is and how its been configured. Can you post a more complete code example that someone could actually run and see the problem – Paul Rooney Sep 13 '16 at 02:40
  • What is your timeout value set to? – paxdiablo Sep 13 '16 at 02:41
  • I expanded the example. I added the `flush()`, but it didn't help. – Rachie Sep 13 '16 at 02:55

2 Answers2

2

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
Schwub
  • 46
  • 4
0

I couldn't add a commend so I will just add this as an answer. You can reference this stackoverflow thread. Someone attempted something similar to your question.

Seems they put their data reading in a loop and continuously looped over it while data came in. You have to ask yourself one thing if you will take this approach, when will you stop collecting data and jump out of the loop? You can try and continue to read data, when you are already collecting, if nothing has come in for a few milliseconds, jump out and take that data and do what you want with it.

You can also try something like:

While True:
    serial.flushInput()
    serial.write(command)
    incommingBYTES = serial.inWaiting()
    serial.read(incommingBYTES)
    #rest of the code down here
Community
  • 1
  • 1
Xavid Ramirez
  • 216
  • 2
  • 7
  • in pyserial 3.3 the serial.inWaiting() mentioned in your code snippet is a property. serial.in_waiting (just for clarification, if someon comes across this answer) – jodá May 25 '23 at 11:52