在Python中的某段时间内通过串口等待数据

时间:2017-03-28 01:48:57

标签: python python-3.x serial-port pyserial

我必须在一定时间内通过串口等待一定大小的数据。如果我这次获得的数据较少,那么我想避免读取数据。如果我尽早获得足够的数据,那么我想阅读它们并停止等待数据。

我目前的解决方案如下:

serial.open()
start_time = time()
while serial.in_waiting < expected_data_size: # waiting certain size of data
    if time_to_wait < time() - start_time: # time is expired
        serial.close()
        return
data = serial.read(expected_data_size)
serial.close()

但我认为这不是一个好的解决方案,因为比较(在“while”和“if”块中)会发生很多次,而它会等待数据。

请告诉我如何在Python 3中更好地实现它。要使用串口,​​我使用pySerial

提前谢谢!

1 个答案:

答案 0 :(得分:1)

你不需要发明新车轮。 1)当您打开端口时,您应该设置超时。 2)在端口打开后,您应该设置要在“读取”API中读取的数据大小。

读取API将返回数据大小,如果超时则返回较少的数据。

参见文档中的示例:

>>> with serial.Serial('/dev/ttyS1', 19200, timeout=1) as ser:
...     x = ser.read()          # read one byte
...     s = ser.read(10)        # read up to ten bytes (timeout)