Python serial.readline() not blocking



我试图使用硬件串行端口设备与Python,但我有时间问题。如果我向设备发送一个审讯命令,它应该会以数据回应。如果我试图读取传入的数据太快,它什么也收不到。

import serial
device = serial.Serial("/dev/ttyUSB0", 9600, timeout=0)
device.flushInput()
device.write("command")
response = device.readline()
print response
''

readline()命令没有阻塞并等待新行。是否有一个简单的解决方法?

readline()使用与传递给serial.Serial()相同的超时值。如果您希望readline阻塞,只需删除timeout参数,默认值为None

你也可以在调用readline()之前将其设置为None,如果你想有一个超时打开设备:

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

我不能添加一个推荐,所以我将添加这个作为答案。你可以引用这个stackoverflow线程。有人试图做类似于你问题的事情。

似乎他们把数据读取放在一个循环中,并在数据传入时不断循环。你必须问自己一件事,如果你采用这种方法,你什么时候会停止收集数据并跳出循环?你可以尝试继续读取数据,当你已经在收集数据的时候,如果几毫秒内没有数据,跳出来,获取数据,做你想做的事情。

你也可以尝试这样做:

While True:
    serial.flushInput()
    serial.write(command)
    incommingBYTES = serial.inWaiting()
    serial.read(incommingBYTES)
    #rest of the code down here

最新更新