3

I would like to read data coming and Arduino on a serial port on intervals. So essentially something like

  1. Take a reading
  2. Wait
  3. Take a reading
  4. Wait
  5. Take ...

etc.

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)

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.

Sample output:

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.

I am currently using Python for this but am open to other languages.

4

2 に答える 2

5

次の読み取りを実行する前に、入力バッファーにあるものを取り除きたい場合は、s.flushInput() で入力バッファーをフラッシュできます (s.inWaiting() で入力バッファーのバイトをチェックすることもできます)。 )。

そのため、flush 呼び出しを追加すると、その瞬間から到着したバイトを確実に読み取ることができます。

while True:
    s.flushInput()
    print s.readline()
    time.sleep(.5)

読み取りタイムアウトの使用を検討することもできます (serial.Serial オブジェクトをタイムアウト パラメータで作成する場合)。この場合、タイムアウトが発生したときに空の読み取り値を処理する必要がありますが、送信者が何らかの理由で停止した場合、リーダーが永遠に待機しないことを保証します。

于 2013-11-09T11:56:23.257 に答える