Skip to content

Instantly share code, notes, and snippets.

@ericjforman
Created March 21, 2013 16:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ericjforman/5214234 to your computer and use it in GitHub Desktop.
Save ericjforman/5214234 to your computer and use it in GitHub Desktop.
Sensor smoothing function
/* 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 sensor inputs 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);
// use either or both values:
//Serial.print(rawVal);
//Serial.print("t");
Serial.print(int(smoothedVal)); // * int() 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
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment