Arithmetic mean for sensor This is the code I am currently using, but I want to add an arithmetic
mean to it. My goal is: when the pin A0 reads 5 values, I get the average
on which the fan and led will depend to be turned on and off, instead of
5 separate measurements.

int tempPin = A0;
int fan = 3;
int led = 8;
int temp;
int tempreal;
int tempMin = 20;
int tempMax = 30;

void setup() 
{
  Serial.begin(9600);
  pinMode(fan, OUTPUT);
  pinMode(led, OUTPUT);
  pinMode(tempPin, INPUT);
}

void loop() 
{
  temp = analogRead(tempPin);
  tempreal = temp * 0.48828125;
  delay(1);
  if(tempreal &gt; tempMax)
  {
    digitalWrite(fan,HIGH);
    digitalWrite(led,LOW);
    delay(1);
  } 
  else if (tempreal &lt; tempMin)
  {
    digitalWrite(fan,LOW);
    digitalWrite(led,HIGH);
    delay(1);
  } 
  else if (tempreal &gt;  tempMin &amp;&amp; tempreal &lt;  tempMax)   
  {
    digitalWrite(fan,LOW);
    digitalWrite(led,LOW);
    delay(1);
  }
}


Edit by Edgar Bonet – The OP added in a comment to my answer:

“I tried [averaging consecutive readings]. It worked as you would expect
but it still does not solves my problem. My sensor is only getting right
values in the beginning of the scanning and then it varies. That is why
I wanted to make average value but it still does not work. Sadly I think
I wont be able to change sensor, but is there any other way to
camouflage this problem?”

Below is a screenshot showing both correct (✓) and incorrect (✗)
readings:
A fixed sampling window can be hard to manage, especially if you want the calculation to be recursive, for space and speed considerations. 

You can achieve similar results via exponential smoothing. 

Yn = (1−α) Yn−1 + α Xn

Where Yn is the smoothed outcome, Xn is the current measurement, and α is the weight.

With some thoughts, it can be done with integers and without loss of precision.

edit: i ran a comparison of exponential smoothing vs. (fixed window) moving average. The moving average algorithm was written to be recursive for maximal speed.

the sampled data is a simulated sine wave:

1000 * sin(2pi*n/100) + 100 * noise. n = 0..19999, and noise = -0.5...+0.5.

So snr = 1000 / 50 = 20:1, or about 5 digits. far worse than what you would encounter in a 10-bit adc.


the window I picked is 4.

As you can see, both approaches closely resemble each other. exponential smoothing uses much less ram and is also much faster. older data has lower weight on the output, something generally desirable in most applications.