by jamie allen

A simple moving average that takes half of the old average in to account, adding it to half of each new sample. This is a 'standard' filtration technique and does not effect your converted-sample output rate.


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 currentAVG = 0; //current average
int lastAVG = 0; //storage for the ‘last’ average value
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

val = analogRead(potPin); // read the value from the sensor
delay(20);
currentAVG = (val + lastAVG)/2;
lastAVG = currentAVG;

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

Serial.print(”Moving Average: “);
Serial.println(currentAVG, DEC); // print as an ASCII-encoded decimal
}