Help

Hello everyone,

I am facing a terrible in if condition as I suppose. I am working on a system to turn on a fan when the temperature reach a certain level using DHT11 sensor and relay module. The problem is the relay is not switched on although it works in the Setup void properly for 2 seconds. So I think there is a problem in If condition, can you figure it out?

Here is the code,

#include<dht.h>
dht DHT;

// if you require to change the pin number, Edit the pin with your arduino pin.
#define DHT11_PIN 2
int relay = 7;

void setup() {
  pinMode(relay, OUTPUT);
  digitalWrite(relay, LOW);
  delay(2000);
  digitalWrite(relay, LOW);
  Serial.begin(9600); 

}
void loop() { // READ DATA

float chk = DHT.read11(DHT11_PIN);


  if (chk >= 25)
     {
      digitalWrite(relay, LOW);
      Serial.println(" Fan is on ");
        }

  else
     {
       digitalWrite(relay, HIGH);
         }
Serial.println(" Temparature ");
Serial.println(DHT.temperature, 1);
Serial.println(" Humidity " );
Serial.println(DHT.humidity, 1); 

delay (2000);

}

Have you tried printing “chk” to see if the value ever drop below 25?

Does the example sketch that comes with the library work with your DHT device?

Where is
#define DHTTYPE DHT11 // DHT 11
Check example.

The problem was with "chk" since its value is continuously = -1 , I thought that chk must have the value of the temperature, but it truth is another thing.

it finally works since I changed the code into the following:

float chk = DHT.read11(DHT11_PIN);


  if (DHT.temperature >= 25)
     {
      digitalWrite(relay, LOW);
        }
   else 
       { 
        digitalWrite(relay, HIGH);
       }

Sincerely. :slight_smile:

You might like to think of adding some hysteresis to that. As it stands, if the temperature warms to 25 the fan will turn on, but if it sits at around that temperature and drops back to 24.9 then up to 25 again, the relay and the fan will be off-ing and on-ing like maniacs.

So perhaps have it turn on at 26 and off at 25, or on at 25 off at 24, something like that?

What is the point of this?

  digitalWrite(relay, LOW);
  delay(2000);
  digitalWrite(relay, LOW);

neiklot:
So perhaps have it turn on at 26 and off at 25, or on at 25 off at 24, something like that?

What I've done for one of my projects in the past (an indoor grow room automation system), is if the temperature (or humidity or whatever) hits the mark to enable fans or other devices, I force the fans to stay on for a set amount of time, (eg 15 or 30 minutes) regardless if the temp drops below the off threshold.

After that forced time, the temp is checked again, and if temp is still too high, keep the fan running, otherwise turn it off.

It ensures that the relays aren't being triggered repeatedly if the temp stays right near the on/off point