问题描述
我想定期读取来自串行端口的数据和Arduino.所以本质上是
I would like to read data coming and Arduino on a serial port on intervals. So essentially something like
- 阅读
- 等待
- 读书
- 等待
- 接...
等
我面临的问题是端口将缓冲其信息,因此,一旦我调用等待功能,串行端口上的数据就会开始缓冲.等待功能完成后,我尝试再次读取数据,但我正在从缓冲区的开头读取数据,数据不再是当前数据,而是在等待功能开始时大致进行读取.
The problem I am facing is that the port will buffer its information so as soon as I call a wait function the data on the serial port will start buffering. Once the wait function finishes I try and read the data again but I am reading from the beginning of the buffer and the data is not current anymore, but instead is the reading taken at roughly the time the wait function began.
我的问题是,是否有一种我不知道的方法,可以忽略在等待期间读取的部分数据,而仅读取当前在串行端口上传递的数据?
My question is whether there is a way that I am unaware of to ignore the portion of data read in during that wait period and only read what is currently being delivered on the serial port?
到目前为止,我有类似的东西:
I have this something analogous to this so far:
import serial
s = serial.Serial(path_to_my_serial_port,9600)
while True:
print s.readline()
time.sleep(.5)
出于解释的目的,我让Arduino输出自开始循环以来的时间.通过python代码,每次调用的时间应该相隔半秒.通过串行输出,时间以不到一毫秒的增量递增.无论睡眠时间如何,这些值都不会改变.
For explanation purposes I have the Arduino outputting the time since it began its loop. By the python code, the time of each call should be a half second apart. By the serial output the time is incrementing in less than a millisecond. These values do not change regardless of the sleep timing.
示例输出:
504
504
504
504
505
505
505
...
出于对最终目标的了解,我想测量端口的值,等待一段时间,然后查看该值,然后再等待,再查看该值,然后再等待.
As an idea of my end goal, I would like to measure the value of the port, wait a time delay, see what the value is then, wait again, see what the value is then, wait again.
我目前正在为此使用Python
,但可以使用其他语言.
I am currently using Python
for this but am open to other languages.
推荐答案
如果要在执行下一次读取之前清除输入缓冲区中的内容,可以使用s.flushInput()刷新输入缓冲区. (您也可以使用s.inWaiting()检查输入缓冲区中的字节).
If you want to get rid of what may be in the input buffer before you perform your next read, you can flush your input buffer with s.flushInput() (you could also check the bytes in your input buffer with s.inWaiting()).
因此,添加flush调用将确保您读取从那一刻起到达的所有字节:
So, adding the flush call will make sure that you read whatever bytes arrive from that moment:
while True:
s.flushInput()
print s.readline()
time.sleep(.5)
您可能还需要考虑使用读取超时(在使用timeout参数创建您的serial.Serial对象时).在这种情况下,您将需要在超时时处理空的读数,但是您可以保证,如果发件人由于任何原因停止阅读,您的阅读器将不会永远等待.
You may also want to consider using a read timeout (when you create your serial.Serial object as, with timeout parameter). In this case you would need to deal with empty readings when there is a timeout, but you would guarantee that if the sender stops for any reason, your reader will not be waiting forever.
这篇关于读取串行端口-在一段时间内忽略部分写入串行端口的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!