#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include "DHT.h"
// Define the pin and sensor type
#define DHTPIN 4 // DHT sensor data pin is connected to GPIO 4
#define DHTTYPE DHT22 // Using the DHT22 temperature and humidity sensor
// Initialize the DHT sensor object
DHT dht(DHTPIN, DHTTYPE);
// Initialize the LCD I2C (Address 0x27, 16 columns, 2 rows)
LiquidCrystal_I2C lcd(0x27, 16, 2);
void setup() {
// Start serial communication for debugging
Serial.begin(115200);
// Initialize the LCD screen
lcd.init();
lcd.backlight(); // Turn on the screen light
// Start the DHT sensor
dht.begin();
// Display welcome message on LCD
lcd.setCursor(0,0);
lcd.print("DHT22 Sensor");
lcd.setCursor(0,1);
lcd.print("Initializing...");
delay(2500); // Wait for 2.5 seconds
lcd.clear(); // Clear the screen
}
void loop() {
// Read humidity and temperature values from the sensor
float humidity = dht.readHumidity();
float temperature = dht.readTemperature(); // Temperature in Celsius
// Check if the sensor data is valid
if(isnan(humidity) || isnan(temperature)) {
Serial.println("Failed to read from DHT22 sensor!");
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Reading Error");
lcd.setCursor(0, 1);
lcd.print("Check Sensor!");
}
}
[5/2 20.31] .: delay(2500);
return; // Exit the loop and try again
}
// Print values to the Serial Monitor
Serial.print("Temp: ");
Serial.print(temperature);
Serial.print(" °C, Humidity: ");
Serial.print(humidity);
Serial.println(" %");
// Display the data on the LCD screen
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Temp: ");
lcd.print(temperature, 1); // Display 1 decimal place
lcd.print((char)223); // Character code for the degree symbol (°)
lcd.print("C");
lcd.setCursor(0, 1);
lcd.print("Humid: ");
lcd.print(humidity, 1); // Display 1 decimal place
lcd.print("%");
delay(2500); // Wait 2.5 seconds before the next update
}