简体   繁体   中英

Python serial.readline() not blocking

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM