Skip to content

Instantly share code, notes, and snippets.

@giantmolecules
Created April 29, 2017 21:07
Show Gist options
  • Save giantmolecules/d6c486f2a442d715754c43054030e71c to your computer and use it in GitHub Desktop.
Save giantmolecules/d6c486f2a442d715754c43054030e71c to your computer and use it in GitHub Desktop.
/*
* Project moving-average-filter
* Description: Filters out noise
* Author: Brett Balogh
* Date: April 29, 2017
* Copyright: CC-BY-SA-NC
*/
#define SENSOR_PIN 0
const int numValues = 100
int values[numValues];
int sensorValue = 0;
int sumValues = 0;
int averageValue = 0;
void setup(){
// Start serial port for debugging
Serial.begin(9600);
// Initialize values of array
for(int i = 0; i < arraySize(values); i++){
values[i] = 0;
}
}
void loop(){
// Read the sensor
sensorValue = analogRead(SENSOR_PIN);
// pop the new value on the front of the array
values[0] = sensorValue;
// Shift values in array 1 position to the right
// Pops oldest value (highest index) in array off
for(int i = arraySize(values)-1; i > 0; i--){
values[i]=values[i-1];
}
// Sum all values inthe array
sumValues = 0;
for(int i = 0; i < arraySize(values); i++){
sumValues = sumValues+values[i];
}
// Calculate average
averageValue = sumValues/arraySize(values);
// Debug
Serial.print("sensorValue: ");
Serial.print(sensorValue);
Serial.print(" averageValue: ");
Serial.println(averageValue);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment