#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <DHT.h>
// I2C LCD settings (most common address is 0x27; try 0x3F if needed)
LiquidCrystal_I2C lcd(0x27, 16, 2);
// DHT Sensor settings
#define DHTPIN 2 // DHT22 connected to digital pin D2
#define DHTTYPE DHT22 // We're using the DHT22 sensor
DHT dht(DHTPIN, DHTTYPE); // Create DHT object
void setup() {
lcd.init(); // Start the LCD
lcd.backlight(); // Turn on the backlight
dht.begin(); // Start the DHT sensor
lcd.setCursor(0, 0);
lcd.print("Temp & Humidity");
delay(2000); // Wait 2 seconds before starting readings
lcd.clear();
}
void loop() {
float temperature = dht.readTemperature(); // Read temp in Celsius
float humidity = dht.readHumidity(); // Read humidity
// Check if sensor returns valid numbers
if (isnan(temperature) || isnan(humidity)) {
lcd.setCursor(0, 0);
lcd.print("Sensor error");
lcd.setCursor(0, 1);
lcd.print("Try again...");
} else {
lcd.setCursor(0, 0);
lcd.print("Temp: ");
lcd.print(temperature);
lcd.print((char)223); // Degree symbol
lcd.print("C");
lcd.setCursor(0, 1);
lcd.print("Hum: ");
lcd.print(humidity);
lcd.print(" %");
}
delay(2000); // Wait 2 seconds between updates
}