Skip to main content
Arduino

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

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 > tempMax)
 {
 digitalWrite(fan,HIGH);
 digitalWrite(led,LOW);
 delay(1);
 } 
 else if (tempreal < tempMin)
 {
 digitalWrite(fan,LOW);
 digitalWrite(led,HIGH);
 delay(1);
 } 
 else if (tempreal > tempMin && tempreal < 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:

Example readings

Answer*

Draft saved
Draft discarded
Cancel

AltStyle によって変換されたページ (->オリジナル) /