Go Down

Topic: FYI: Exponential Smoothing: (Read 1 time) previous topic - next topic

warren631

This code is useful to smooth noisy sensor signals.  It does not use much memory. 
alpha is the smoothing constant which must be between  0 and 1.  An alpha of 0.01 gives smoothing similar to averaging 100 readings.

Code: [Select]
void loop() {
  raw = analogRead(sensorPin);
  average = alpha * raw + (1-alpha) * average;    //exponential smoothing
  Serial.println(average);   
  delay(1);        // delay in between reads for stability           

}

el_supremo

That doesn't work the way you say. When I read pin A0 on my Duemilanove and print the raw value, it prints 506 or 507, so the average is 506.5.
With your code and an alpha of .01, it takes about two seconds to settle down to 408. This is not even close to the average of 100 readings.

Pete

PeterH

It does work as described  if you initialise the running average with the first raw reading.
I only provide help via the forum - please do not contact me for private consultancy.

el_supremo

It works a lot better when alpha is a value like .8 or .9 and then average doesn't need to be initialized to the current ADC value.

Pete

Go Up