我正在尝试使用Python的硬件串口设备,但我遇到时间问题。如果我向设备发送询问命令,它应该响应数据。如果我试图过快地读取传入的数据,它什么都不会收到。
import serial
device = serial.Serial("/dev/ttyUSB0", 9600, timeout=0)
device.flushInput()
device.write("command")
response = device.readline()
print response
''
readline()
命令没有阻塞并等待新行。有一个简单的解决方法吗?
答案 0 :(得分:0)
我无法添加一个推荐,所以我只想添加一个作为答案。您可以参考this stackoverflow thread。有人试图类似于你的问题。
似乎他们把数据读取放在一个循环中,并在数据进入时继续循环它。如果你采取这种方法,你必须问自己一件事,你何时会停止收集数据并跳出循环?您可以尝试继续读取数据,当您已经收集数据时,如果没有任何内容进入几毫秒,则跳出并获取数据并使用它执行您想要的操作。
您还可以尝试以下方式:
While True:
serial.flushInput()
serial.write(command)
incommingBYTES = serial.inWaiting()
serial.read(incommingBYTES)
#rest of the code down here
答案 1 :(得分:0)
readline()
使用您传递给serial.Serial()
的相同超时值。
如果您希望readline被阻塞,只需删除timeout参数,默认值为None
。
如果您想要暂停设备,可以在调用None
之前将其设置为readline()
:
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