segunda-feira, 10 de novembro de 2014

Creating a digital filter - Smoothing analog input values

If you wanna eliminate noise from your analog inputs, or have smooth variation in reads, you can implement a digital filter following this example:

 int ldrSensor = 2;  
 float rawValue = 0;  
 float withFilter = 0;  
 float variation = 0;  
 float smoothCoeficient = 0.1;  
 void setup()  
 {  
  Serial.begin(9600);  
  rawValue = analogRead(ldrSensor);  
  withFilter = rawValue;  
 }  
 void loop()  
 {  
  rawValue = analogRead(ldrSensor);  
  variation = rawValue - withFilter ;  
  withFilter = withFilter + variation * smoothCoeficient ;  
  Serial.print(int(rawValue));  
  Serial.print(" ");  
  Serial.println(int(withFilter));  
 delay(50);  
 }  

If you set lower smoothCoeficient value, slower will be the changes in your filtered values.

Data output example:

 656 656  
 656 656  
 657 656  
 657 656  
 656 656  
 657 656  
 657 656  
 656 656  
 656 656  
 657 656  
 656 656  
 657 656  
 656 656  
 657 656  

When you have a smoothCoeficient of 0.1, means that only 10% of the last variation will be inserted into filtered value. You may need to change this value to fit your needs.

Nenhum comentário:

Postar um comentário