Interaction Design WikiElectrical Engineering

Signal Filtering

Values from some sensors may be jumpy or erratic. Generally, it's best to first try to solve the problem on the hardware side (is there a floating pin, or bad contact?). If that fails, we can use some code to clean up the values by calculating the running average. Alternatively, we can use the Weighted Moving Average, with more weight on new data and less on older data. This has the advantage of being very lightweight to implement on the Arduino, although we lose some response speed and we don't get a true average. We can easily adjust the ratio of the weighting depending on the amount of noise. 

The blue line indicates the original value, and red is the smoothed value. 

Smoothing
/*
  Weighted Moving Point Average  
  Luke Franzke 
  ZHdK
  2019
*/
#define analogInPin A0  // our sensor input pin 
int weightedAverage = 0; // where we we stored our average values
void setup() {
  // initialize serial communications at 9600 bps:
  Serial.begin(9600);
}

void loop() {
 // read the analog in value:
  int sensorValue = analogRead(analogInPin);
// calculate the weighted moving point average 
// our scaling factor should add up to 1, but this ratio can be adjusted depending on the amount of noise 
  weightedAverage = weightedAverage*0.7;
  weightedAverage += sensorValue*0.3;
  // print both results to the Serial Monitor:
  Serial.print("sensor: ");
  Serial.print(sensorValue);
  Serial.print(",");
  Serial.println(weightedAverage);
  delay(1);  // delay in between reads for stability
}