#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include "DHT.h"
// Define the DHT22 sensor type and the pin it is connected to
#define DHTPIN 4 // ESP32 pin connected to the DHT22 data pin
#define DHTTYPE DHT22 // DHT 22 (AM2302)
// Initialize DHT sensor
DHT dht(DHTPIN, DHTTYPE);
// Initialize the LCD with the I2C address (0x27) and set it to a 16x2 display
LiquidCrystal_I2C lcd(0x27, 16, 2);
void setup() {
// Start the serial communication
Serial.begin(115200);
// Initialize the LCD and turn on the backlight
lcd.begin();
lcd.backlight();
// Initialize the DHT sensor
dht.begin();
// Print the startup message on the LCD
lcd.setCursor(0, 0); // Start at the first row
lcd.print("Temp & Humidity");
delay(2000); // Wait for 2 seconds
}
void loop() {
// Reading temperature and humidity from DHT22 sensor
float humidity = dht.readHumidity();
float temperature = dht.readTemperature();
// Check if any reading failed
if (isnan(humidity) || isnan(temperature)) {
Serial.println("Failed to read from DHT sensor!");
lcd.setCursor(0, 0);
lcd.print("Sensor Error! ");
return;
}
// Print temperature and humidity to Serial Monitor
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.print(" %\t");
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.println(" *C");
// Display temperature and humidity on the LCD
lcd.clear();
lcd.setCursor(0, 0); // First row
lcd.print("Temp: ");
lcd.print(temperature);
lcd.print(" C");
lcd.setCursor(0, 1); // Second row
lcd.print("Hum: ");
lcd.print(humidity);
lcd.print(" %");
// Wait for 2 seconds before taking the next reading
delay(2000);
}