# Average of Number over 24hours

Hey,

I am not very experienced with C++. I want to get the daily average value of a reading coming from an analog sensor. Could any one please post some code that would:

Get and print the average of ‘x’ over 24 hours, where ‘x’ is the value being read from an analog sensor.

I wrote some code for you, it is not tested, but it might help you getting started

///Config
const byte SAMPLE_PIN = 0;
const int NUMBER_OF_SAMPLES_PER_HOUR = 10;

//delay = minutes_in_hour*seconds_in_minute*millisecons_in_second / samples_per_hour
const int SAMPLE_DELAY = (60*60*1000) / NUMBER_OF_SAMPLES_PER_HOUR;
const int TIMES_AS_FAST = 1; //if set to 4, a day will go by four times as fast if you want a day to be an hour set to 24

int index = 0;
int average = 0;

void setup()
{
// initialize serial communication with computer:
Serial.begin(9600);
// initialize all the readings to 0:
}
}

void loop() {

if (index >= NUMBER_OF_SAMPLES_PER_HOUR) {
long sum = 0;
}
// calculate the average:
average = sum / NUMBER_OF_SAMPLES_PER_HOUR;
// send it to the computer (as ASCII digits)
Serial.print("Average last day: ");
Serial.println(average, DEC);
index = 0;
}

delay(SAMPLE_DELAY / TIMES_AS_FAST);
}

One approach to averaging a large number of samples is to use moving average. That is to calculate the average after each and every sample so that at any point in time you know the historic average. The formula for this is as follows:

float avg; // value for moving average
unsigned long n; // number of samples
float t;  // value for current sample

// get sample