1

I have a ultrasonic ping sensor getting output from it in Python. This reading is in a

while True:

so that obviously never stops.

That data is set to a var called 'ping_out'. I need to get the last three readings from ping_out and average them so that I get a var called ping_average. How can I do this?

Thanks!

developius
  • 1,193
  • 9
  • 17
  • Can you show the code that sets 'ping_out'? A queue of length 3 seems to be the appropriate data structure for this. – David Cain Feb 27 '14 at 20:12
  • 1
    Related: http://stackoverflow.com/questions/11352047/finding-moving-average-from-data-points-in-python – kojiro Feb 27 '14 at 20:13
  • ping_out = timepassed * 17000. Timepassed is the time between sending the pulse and recovering it. – developius Feb 27 '14 at 20:15

1 Answers1

4

Use a length 3 deque object:

from collections import deque
last3 = deque(maxlen=3)

while True:
    last3.append(this_ping)  # <-- insert your ping here, of course
    avg = sum(last3) / len(last3)
    print avg
mhlester
  • 22,781
  • 10
  • 52
  • 75
  • Nice. Part of me wants to preoptimize that `len(last3)` bit because you only need to call it a maximum of three times. – kojiro Feb 27 '14 at 20:15
  • i'd wonder how much your optimization would be negated by the overhead of said optimization :) – mhlester Feb 27 '14 at 20:16
  • Thanks so much for the brilliant answer, and extremely quick reply!!!!! And thanks to you too @David for trying :) unfortunately, everyone on here has ridiculously quick typing ;) – developius Feb 27 '14 at 20:22
  • @mhlester I can't imagine it'd be so bad :P https://gist.github.com/kojiromike/9258780 – kojiro Feb 27 '14 at 20:26
  • @kojiro, out of the frying pan and into the fire? – mhlester Feb 27 '14 at 20:38