#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <DHT.h>
// Set the LCD address to 0x27 for a 16x2 display
LiquidCrystal_I2C lcd(0x27, 16, 2);
// Define the DHT sensor type and pin
#define DHTPIN 2 // Pin connected to the DHT22 sensor
#define DHTTYPE DHT22 // DHT22 (AM2302) sensor
DHT dht(DHTPIN, DHTTYPE);
void setup() {
// Initialize the LCD
lcd.begin(16, 2);
lcd.backlight();
// Initialize the DHT sensor
dht.begin();
// Print a welcome message
lcd.setCursor(0, 0);
lcd.print("Temp & Humidity");
delay(2000);
}
void loop() {
// Read temperature as Celsius and Fahrenheit
float temperatureC = dht.readTemperature();
float temperatureF = dht.readTemperature(true);
// Read humidity
float humidity = dht.readHumidity();
// Check if any readings failed
if (isnan(temperatureC) || isnan(humidity)) {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Failed to read");
delay(2000);
return;
}
// Display temperature and humidity
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Temp: ");
lcd.print(temperatureC);
lcd.print((char)223); // Degree symbol
lcd.print("C");
lcd.setCursor(0, 1);
lcd.print("Humidity: ");
lcd.print(humidity);
lcd.print("%");
// Wait 2 seconds before next read
delay(2000);
}