by Jamie Allen

This is a simple 'batch' averaging algorithm. It will work to reduce noise and generally stabilize data, but be aware that you're cycling through your data much more slowly. The 'output' frequency of an algorithm like this is always going to be less than the sampling frequency, so the overall latency of your system can be effected (Latency is the total time it takes between sensor-actuation and desired 'result' of that actuation).


int potPin = 0; // select the input pin for the potentiometer
int ledPin = 13; // select the pin for the LED
int val = 0; // variable to store the value coming from the sensor
int accVal = 0; // accumulation of a sum for averaging
int avg = 0; // average result
int howManyToAverage = 5; //number of individual values to average

void setup() {
pinMode(ledPin, OUTPUT); // declare the ledPin as an OUTPUT
Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
}

void loop() {
int i;

digitalWrite(ledPin, HIGH); // sets the LED off

accVal = 0; // clear the accumulator

for (i=0; i<howManyToAverage; i++)
{
val = analogRead(potPin); // read the value from the sensor

accVal = accVal + val;
//Serial.print("Accumulator: ");
//Serial.println(accVal, DEC); // print as an ASCII-encoded decimal

delay(10);
}

Serial.print("Raw Value: ");
Serial.println(val, DEC); // print as an ASCII-encoded decimal

avg = accVal/howManyToAverage;
Serial.print("Simple Average Value: ");
Serial.println(avg, DEC); // print as an ASCII-encoded decimal

}