Average of Number over 24hours


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 :slight_smile:

const byte SAMPLE_PIN = 0;

//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 readings[NUMBER_OF_SAMPLES_PER_HOUR*24];  

int index = 0;
int average = 0;

void setup()
      // initialize serial communication with computer:
      // initialize all the readings to 0: 
      for (int thisReading = 0; thisReading < NUMBER_OF_SAMPLES_PER_HOUR; thisReading++) {
            readings[thisReading] = 0;          

void loop() { 
      // read from the sensor:  
      readings[index++] = analogRead(SAMPLE_PIN); 

      if (index >= NUMBER_OF_SAMPLES_PER_HOUR) {
            long sum = 0;
            for (int thisReading = 0; thisReading < NUMBER_OF_SAMPLES_PER_HOUR; thisReading++) {
                  sum += readings[thisReading];          
            // 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
  t = analogRead(0);
  // update sample count
  // calculate moving average
  avg += (t - avg) / n;

Note that averaging use floating point in calculations. If after some time (e.g. every 24 hours) you want to start a new averaging period, you simply set number of samples (n) to zero (or one if you want to start off with "current" average at that time).

If you want a continues moving average for the last 24 hours (e.g. from hour 0 to 24, then from 1 to 25 and so forth) you get a good approximation if you stop incrementing - n - once you have reached your first targeted period. So if you collect 1000 samples every 24 hours, you stop incrementing n once you get to 1000.

Thanks for the code!! With your help I was able to get it working!!!