Getting raw data readings from different sensors is usually pretty straightforward. However, before the aqcuired sensor data can be interpreted, it is usally advisable to remove any unwanted noise (caused by bad power supplies, radio frequency interference or similar).
A digital low-pass filter is a simple and flexible way to clean up and smooth sensor data, here is an example:
//Simple IIR (Infinite Impulse Response) filter example for smoothing sensor values //(c)left 2016 // Kristian Gohlke // Bauhaus-Universität Weimar // Released under a CC-BY-SA License int sensorValue = 0; int lastSensorValue = 0; //this value adjusts how much a new value affects the filtered result: float weight = 0.5; void setup() { Serial.begin(9600); } void loop() { //get raw sensor reading and pass the value to the filter function sensorValue = filter(analogRead(A0), weight, lastSensorValue); //store current sensorvalue for the next iteration of the loop lastSensorValue = sensorValue; Serial.println(sensorValue); delay(20); } //weighted average (IIR) filter (also accepts integers) float filter(float rawValue, float weight, float lastValue) { float result = weight * rawValue + (1.0 - weight) * lastValue; return result; }
The filter can also be used on multiple sensor readings in a single line of code:
//Simple IIR (Infinite Impulse Response) filter example for smoothing sensor values //SINGLE LINE EXAMPLE //(c)left 2016 // Kristian Gohlke // Bauhaus-Universität Weimar // krigoo@gmail.com // Released under a CC-BY-SA License int sensorValueA = 0; int sensorValueB = 0; void setup() { Serial.begin(9600); } void loop() { //filter values in ONE LINE OF CODE using no additional variables: sensorValueA = filter(analogRead(A0), 0.5, sensorValueA); sensorValueB = filter(analogRead(A1), 0.1, sensorValueB); //sensorValueC = filter(analogRead(A2), ... //etc pp... //HINT: use this with the Serial Plotter in your Arduino IDE! Serial.print(sensorValueA); Serial.print(" "); Serial.print(sensorValueB); Serial.println(); delay(20); } //weighted average (IIR) filter (also accepts integers) float filter(float rawValue, float weight, float lastValue) { float result = weight * rawValue + (1.0 - weight) * lastValue; return result; }
For a more detailed technical explanation and other digital filtering options, see page 18-29 from the application note below:
http://ww1.microchip.com/downloads/en/AppNotes/00001334B.pdf