How to write code for a rolling average

Hello there

I'm attempting to read a pressure sensor and I've got the basic code in to read the code and if the reading drops below a threshold an LED goes off.

But, I'm looking to have my HUZZAH create a rolling average of the readings and then set up a %change to trigger the LED going off.

So what is the code, or where should I look to find it, so that each loop:

  1. reads the current value
  2. creates an average of the last N values from 1
  3. compares the value from 1 to the average from 2
    3a) If current value is <= (the average from 2-%) turn on the LED
  4. add the current value from 1 to the average

Thank you

The trick is to put all the data into the array and then don't move it. The naive method is to move all the values down so that there's space at the top to put the new value in. Your program will spend too much time just moving data.

The clever way just keeps an index pointing to the oldest item. When a new item comes in, overwrite the oldest item and move the index to the next-oldest. Wrap around to zero when you run off the end of the array.

The averager is independent of the data-storer. You can average all values in the array at any time, without even knowing which one is the oldest.

The simplest way to write code for a running/rolling average is to NOT write code, when such code already exists.

http://playground.arduino.cc/Main/RunningAverage