When the IF statement is true my lcd screen crashes

Hello everyone, I'm rather new to Arduino coding, and any help would be greatly appreciated.
I wrote a simple code just for fun, as you will see the code uses the temperature and humidity sensor and print the value on an lcd screen and if the temperature reaches above 29 degrees it should turn on the FAN.
The problem that I encounter is that: as long as the statement is false it works, but as soon as the statement becomes true, the FAN turns on, but after a few seconds the output to the lcd screen seams to crash somehow.


#include "DHT.h"
#define DHTPIN 2
#define DHTTYPE DHT11
#include <LiquidCrystal.h>
#define FAN 3

LiquidCrystal lcd(7, 8, 9, 10, 11, 12);

DHT dht(DHTPIN, DHTTYPE);



void setup() {
  // put your setup code here, to run once:
  lcd.begin(16, 2);
  pinMode(FAN, OUTPUT);
  
  
  dht.begin();
  
}

void loop() {
  // put your main code here, to run repeatedly:
    
    
    delay(50);
    float h = dht.readHumidity();
    float t = dht.readTemperature();
      
      lcd.setCursor(0, 0);
      lcd.print(String("Humid.") + String(h) + String( " % "));
      lcd.setCursor(0, 1);
      lcd.print(String("Temp.") + String( t) + String( " C "));
    if (t >= 29 ) 
     
     {
      
      digitalWrite(FAN, HIGH);
      
    }
     else
    {
      
      digitalWrite(FAN, LOW);
    
    }

    
}


Thanks in advanced for any useful insight..!!

Welcome to the forum

How much current does the fan draw when you turn it on ?

Are you aware that an Arduino pin can only supply a limited current and is not designed to be a power supply for motors ?

how is your fan wired up? How are you powering it? You can't drive it directly from your arduino. I would guess that when you turn on the fan, it generates some electrical noise that messes with the i2c display, but that is just a guess.

A schematic, even hand drawn would be useful

Thank you for the support, I was powering it directly over the Arduino, and probably the was the problem, now im going over a relay and everything seams to work well.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.