Code for a rolling average Below is some code I wrote to find the rolling average of a temp sensor hooked up to an arduino and display it to an lcd display. My issue is that for the first minute it is running, the average is not correct. It starts at 0 and then progresses up to where it should be (~85F) in increments of approximately 3. After the first minute it is fine and works as it should.

What I want the code to do is to simply take the average of the sum of the values that have been recorded in the first minute.

My knowledge of C is fairly limited(I only had a semester long class on it) so that is why it is simple. I am a mechanical engineering student and this code is for project at my internship.

#include &lt;Adafruit_MLX90614.h&gt;
Adafruit_MLX90614 tempSensor;

#include &lt;Wire.h&gt;
#include &lt;LCD.h&gt;
#include &lt;LiquidCrystal_I2C.h&gt;

LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

Adafruit_MLX90614 mlx = Adafruit_MLX90614();

double array[30];
double rollingaverage=0;
int i=0, j=0;
double sum=0;
double newreading;
void setup() {

  Serial.begin(9600);
  lcd.begin(20,4);
  mlx.begin();
  Wire.begin();

}

void loop() {
  if(j=0){
      newreading = mlx.readObjectTempF();
      array[i] = newreading;
      sum += array[i];
      if(i&gt;0){
          rollingaverage = sum/(i+1);
      }
      j=1;
  }
  else{
      newreading = mlx.readObjectTempF();
      array[i] = newreading;
      if(i &lt; 29){ //wraps i back around to 0 if it is at 29 to subtract the oldest value
          sum = sum + array[i] - array[i+1];
          rollingaverage = sum/30;
      }
      else{
          sum = sum + array[i] - array[0];
          rollingaverage = sum/30;
          i=0; //reset index to 0
      }
  }
  i++;

  lcd.clear();
  lcd.print("Belt: "); lcd.print(rollingaverage);
  lcd.setCursor(1,2);
  lcd.print("Air: "); lcd.print(mlx.readAmbientTempF());

delay(2000);
}


Its not a huge deal because it works fine after the first minute, it is just annoying that I can't figure out why it doesn't work as intended in the first minute. Thanks
Your problem stems from you starting out with 30 values of 0 which you include in your average.  You have to take that into account and ignore those values, dividing your total by only the number of actual values you have.

I have a library that does it all for you that would make things easier for you:


https://github.com/MajenkoLibraries/Average