by jamie allen jane 15, 2007

This is a more sophisticated way of applying various amount of filtering to incoming values. in effect, the "3" and "7" (these integers must add up to 10) are relative weightings being applied to new incoming values, and the old, accumulated average value. you can think of it like this: if you have a lot of faith in your incoming values (i.e.: they're not noisy), you should include more of the 'fresh' value. if you don't have a lot of faith in your incoming values (i.e.: they are noisy), then include less of the 'fresh' value and more of the prior average.

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 lastVal = 0;  //storage for the 'last' analog input 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

  //currentAVG = 0.7*val + 0.3*lastVal; //this is memory INTENSIVE, but a more accurate average
  currentAVG = (7*val + 3*lastVal)/10; //almost the same as the above but using integer math  
  lastVal = val;

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

  Serial.print("Weighted Average: ");
  Serial.println(currentAVG, DEC);  // print as an ASCII-encoded decimal