Pages: [1]   Go Down
Author Topic: FYI: Exponential Smoothing:  (Read 875 times)
0 Members and 1 Guest are viewing this topic.
Offline Offline
Full Member
***
Karma: 1
Posts: 105
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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:
void loop() {
  raw = analogRead(sensorPin);
  average = alpha * raw + (1-alpha) * average;    //exponential smoothing
  Serial.println(average);   
  delay(1);        // delay in between reads for stability           

}
Logged

Offline Offline
Edison Member
*
Karma: 43
Posts: 1553
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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
Logged

Where are the Nick Gammons of yesteryear?

UK
Offline Offline
Shannon Member
****
Karma: 222
Posts: 12541
-
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

It does work as described  if you initialise the running average with the first raw reading.
Logged

I only provide help via the forum - please do not contact me for private consultancy.

Offline Offline
Edison Member
*
Karma: 43
Posts: 1553
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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
Logged

Where are the Nick Gammons of yesteryear?

Pages: [1]   Go Up
Jump to: