Created
March 21, 2013 16:05
-
-
Save ericjforman/5214234 to your computer and use it in GitHub Desktop.
Sensor smoothing function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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