Hi Liudr,

Simplest form of a running average can be done by this code that builds upon the previous running average

float alpha = 0.7; // factor to play with

value = alpha * measurement + (1-alpha) * value;

This can be done in integer math too. The division by 256 is a shift-right 8, which is faster than say division by 100.

int alpha = 178;

value = (alpha * measurement + (256 - alpha) * value )/ 256; // watch the ()

If you need a more accurate running average, in concreto from the last X measurements you need an array to hold them. This array acts as a circular buffer and with every new measurement the oldest is removed. Then the running average is the sum of all elements divided by the count. The code will be something like this:

long runningAverage(int M)

{

#define LMSIZE 10

static int LM[LMSIZE]; // LastMeasurements

static byte index = 0;

static long sum = 0;

static byte count = 0;

// keep an updated sum to improve speed.

sum -= LM[index];

LM[index] = M;

sum += LM[index];

index = index % LMSIZE;

if (count < LMSIZE) count++;

return sum / count;

}

Drawback of this code is that this array to hold the values can become quite large, if you have one measurement per second and you want a running average per minute you need an array of 60; an average per hour would need an array of 3600 ints (floats or longs). That couldn't be done this way on an Arduino. However by building a 2 stage average it can be approached quite well (not for all measurements). In psuedo code:

every second: rapm = runningAverageMinute(measurement);

every minute: raph = runningAverageHour(rapm);

As a new internal static array is needed for every runningAverage, this screams to implement this as a class

Maybe this helps.

PS, I' will look if I can update the statistics lib with this code or add it as a separate class to the playground article.