#include <LiquidCrystal_I2C.h> // DHT sensor library for DHT11/ DHT22
#include <WiFi.h> // ESP32 Wi-Fi library
#include "DHT.h" // DHT sensor driver library
// Define variables for LCD
#define I2C_ADDR 0x27 // LCD I2C address (Typically is 0x27 or 0x3F)
#define LCD_COLUMNS 16 // Number of LCD columns
#define LCD_LINES 2 // Number of LCD lines
// Define DHT sensor type and pin
#define DHTPIN 4 // DHT22 sensor connected to GPIO4
#define DHTTYPE DHT22 // Use DHT22 type
DHT dht(DHTPIN, DHTTYPE); // Create DHT sensor object
LiquidCrystal_I2C lcd(I2C_ADDR, LCD_COLUMNS, LCD_LINES); // Create LCD object
// Wi-Fi credentials (Wokwi provides free virtual Wi-Fi)
const char* ssid = "Wokwi-GUEST"; // Use "Wokwi-GUEST" for simulation
const char* password = ""; // No password needed for Wokwi Wi-Fi simulation
void setup() {
Serial.begin(115200); // Initialise serial comunication
dht.begin(); // Initialize DHT sensor
lcd.init(); // Initialise LCD
lcd.backlight(); // Turn on LCD backlight
// Connect to Wi-Fi
WiFi.begin(ssid, password); // Start Wi-Fi connection
Serial.print("Connecting to Wi-Fi...");
while (WiFi.status() != WL_CONNECTED) { // Wait until connected
delay(1000); // Wait for Wi-Fi to connect and print '.' symbol (1 seconds)
Serial.print(".");
}
Serial.println("\nConnected to Wi-Fi!");
Serial.println("ESP32 IP Address: " + WiFi.localIP().toString()); // Print ESP32's IP address
}
void loop() {
// Read temperature fromm virtual DHT22
float temperature = dht.readTemperature(); // Temperature in Celsius
float humidity = dht.readHumidity(); // Humidity in %
// Check whether the data is valid
if (isnan(temperature) || isnan(humidity)) {
Serial.println("Failed to read from DHT sensor!");
} else {
// Display data on LCD
lcd.setCursor(0, 0); // Set cursor to column 0, row 0
lcd.print(" Temp: " + String(temperature, 1) + "\xDF" + "C ");
lcd.setCursor(0, 1); // Set cursor to column 0, row 1
lcd.print("Humidity: " + String(humidity, 1) + "% ");
// Print result
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.print("°C | Humidity: ");
Serial.print(humidity);
Serial.println("%");
}
delay(5000); // Update every 5 seconds
}