Average of Sensor Readings

Hi friends

i am beginner in Arduino and I need help.

I am doing Project MLX90615 temperture sensor with display.

it worked but I need the The average .I wrote this code but I got ten times of the last number .

Can someone correct the code?

I am gratefull
here the Code
Hier mein CODE:

#include <LiquidCrystal.h>
#include “MLX90615.h”
#include <I2cMaster.h>

#define SDA_PIN A4 //define the SDA pin
#define SCL_PIN A5 //define the SCL pin

SoftI2cMaster i2c(SDA_PIN, SCL_PIN);
MLX90615 mlx90615(DEVICE_ADDR, &i2c);

const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
double av;
int counter=0;
int anzahl=10;
double sum=0;

void setup()
{
Serial.begin(9600);
}

void loop()
{

double objTem=mlx90615.getTemperature(MLX90615_OBJECT_TEMPERATURE);
Serial.print("Object : ");
Serial.println(objTem);
counter++;
if(counter==10)
{
for(int i=0; i<anzahl; i++)
{
sum=sum+objTem;
counter=0;
}
av = sum / anzahl;
Serial.print(“AVERAGE”);
Serial.println(av);

}
delay(1000);

}

You're not updating "objTem" in the for-loop.

The average of 10 times the same number is that number.

Pieter

Cross-post of Durchschnitt von Sensorwerten(Temperatur) - Deutsch - Arduino Forum

How can I do it?
I tried to write double objTem=mlx90615.getTemperature(MLX90615_OBJECT_TEMPERATURE); in the for loop but it didn't work
If you correct the code I would be gratefull

Stick some print statements in your code so that you can see where the program is going and how variables like counter av and sum are changing - then look at the output and think about what is happening.

You also forgot to set 'sum' to zero before the loop.

Hints:

sum = sum + mlx90615.getTemperature(MLX90615_OBJECT_TEMPERATURE);

Serial.println(av);
sum = 0;

sum = ( sum + mlx90615.getTemperature(MLX90615_OBJECT_TEMPERATURE)) /2; makes a continuous rolling average; with no need to manage a variable holding a count.

Idahowalker:
sum = ( sum + mlx90615.getTemperature(MLX90615_OBJECT_TEMPERATURE)) /2; makes a continuous rolling average; with no need to manage a variable holding a count.

This is an exponential moving average with a coefficient of 0.5. It doesn't behave like the original simple moving average, and won't do a very good job smoothing out the measurements.

See this comparison between the EMA and the SMA

Simple Moving Average Arduino/C++ implementation
Exponential Moving Average Arduino/C++ implementation