h1

Handy Function

November 5, 2015

A while back I wrote this handy function for Arduino called rolling average.  This is a good function to have when working with sensors from a weather station.

It could easily be adapted to have an array with 24 objects in it to average something like light levels or sunshine over a day.  To do this I would change  int sensorReadings[10]; to int sensorReadings[24]; and long interval = 2000; to long interval = 3600000;.  This way it updates once an hour for 24 hours.

I find using a light sensor is an easy to test that it works correctly.

I set it up like this – https://learn.adafruit.com/photocells/using-a-photocell

// 3/5/15 Rolling Average
// Keep a rolling average on a light sensor hooked to analog pin 4

int sensorReadings[10];
int lightSensor = 4;
int val;
int avg;
int y;
long previousMillis = 0;
long interval = 2000;      // how often to update rolling average?

void setup() {
Serial.begin(9600);
}
void loop () {
int answer;
unsigned long currentMillis = millis();
if (currentMillis – previousMillis > interval) {
previousMillis = currentMillis;
answer = rollingAvg ();
Serial.print(F(“Rolling avg = “));
Serial.println(answer);
}
}

int rollingAvg () {
int result;
val = analogRead(lightSensor);

if (y == 0) {
y = 1;
for (int i = 0; i <= 9; i++) {
sensorReadings[i] = val; // fill in array first time around then ignore
}
}
else
{
for (int i = 0; i <= 9; i++) {
if (i > 0) {
sensorReadings[i – 1] = sensorReadings[i]; // shift array to left
}
}
sensorReadings[9] = analogRead(lightSensor);
for (int i = 0; i <= 9; i++) {
avg = avg + sensorReadings[i];
}
avg = (avg / 10);
result = avg;
avg = 0;
return result;
}

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: