Smoothing

Smoothing of e.g. sensor readings to be displayed in a graph can be done in several ways. A rolling average, sometimes called a moving average, is one way of doing that. The arduino pages contain a program by David Mellis, modified by Tom Igoe that illustrates this: it stores values in a 10 value array and divides the sum by 10. Whenever the array is full it removes one value and adds a new one.

Sadly there is a fundamental flaw in this program:

For the initial 10 readings, the result is simply wrong: when the program starts, the array is empty. A value is read into it, and the sum of the array is then divided by 10. Suppose the analog source is quite stable and always gives a reading of 5. Then the first 10 results of the program will be: 5×9*0=5  ->/10=0.5 (rounded t0 0)
5+5+8*0=10 ->/10=1
5+5+5+7*0=15 ->/10=1.5  (rounded to 1)
etc. etc.
Given the fact that the readings are taken with a 1 microsecond delay, that might not be a huge problem, but in that case there are simpler ways, without the need for an array to smooth the readings. For instance like this:

int ReadSensor(){
  int i;
  int sval = 0;

  for (i = 0; i < 10; i++){
    sval = sval + analogRead(0);
  }

  sval = sval / 10;    // average
 
  return sval;
}

strictly speaking this only gives a moving average during this loop and then 10 completely new values are averaged, but at the 1 microsecond interval of the original program that would virtually be the same.

The results in the original program do become a nuisance when you take readings at say 1 minute intervals and you do not want to wait 10 minutes before you get correct data. Fortunately the program can be simply modified to correct for the mistake: for the first 10 readings we divide by the active indexnumber and only after that we divide by the total number of readings (10). We can simply do that by setting a flag:

and then calculate results like so: