Smoothing sensor input

gvps_smooth

Analog sensor input (flex, distance, sound, etc.) often has noise or jitter in the data it provides. Some of this can be improved in hardware, but often it’s easier to do in code. There is a smoothing example built in to the Arduino, and a smoothing function on the Arduino site. Here is my own version which I think is simpler and cleaner, especially if you want to smooth multiple sensors.

/* Sensor smoothing
   by Eric Forman [www.ericforman.com]
   Original version 2008, updated May 2012

   Smooths sensor readings by adding only a fraction of new values.
   The more the new value is divided, the smaller the change, thus a smoother result
   As with any smoothing function, the more you smooth, the slower the response time
*/

int   sensorPin = 0;                    // sensor input pin
int   rawVal = 0;                       // sensor raw value
float smoothedVal = 0.0;                // sensor smoothed value
//float smoothedVal2 = 0.0;             // add additional sensors if you want
float smoothStrength = 5;               // amount of smoothing (default 10)

void setup() {
  Serial.begin(9600);
}

void loop() {
    rawVal = analogRead(sensorPin);
    delay(10);                          // tiny delay to give ADC time to recover

    smoothedVal = smooth(rawVal, smoothedVal);

    // you probably will only use the smoothed value, but print both to compare:
    Serial.print(rawVal);
    Serial.print(",");
    Serial.print(round(smoothedVal));     // * truncates float decimal places *
    Serial.println();
}

float smooth(int t_rawVal, float t_smoothedVal) {
    return  t_smoothedVal + ((t_rawVal - t_smoothedVal) + 0.5) / smoothStrength;  // +0.5 for rounding
}

Try this with the GraphMultiple example in Processing so you can visually see the difference. Be sure to change the number of variables expected to 2 instead of 3, e.g.:

https://github.com/ericjforman/GraphMultiple_p3/tree/2-sensor-example

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a website or blog at WordPress.com

Up ↑

%d bloggers like this: