#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <DHT.h>
// Define the LCD address and size (16 columns and 2 rows)
LiquidCrystal_I2C lcd(0x27, 16, 2);
// Define the DHT sensor type and pin
#define DHTPIN 2
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
void setup() {
// Initialize the LCD
lcd.init();
lcd.backlight();
// Initialize the DHT sensor
dht.begin();
// Print a welcome message on the LCD
lcd.setCursor(0, 0);
lcd.print("DHT22 Sensor");
lcd.setCursor(0, 1);
lcd.print("Initializing...");
delay(2000);
}
void loop() {
// Read the temperature and humidity from the DHT22 sensor
float humidity = dht.readHumidity();
float temperature = dht.readTemperature();
// Check if any reads failed and exit early (to try again)
if (isnan(humidity) || isnan(temperature)) {
lcd.setCursor(0, 0);
lcd.print("Failed to read");
lcd.setCursor(0, 1);
lcd.print("from sensor!");
return;
}
// Clear the LCD and print the temperature and humidity
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Temp: ");
lcd.print(temperature);
lcd.print(" C");
lcd.setCursor(0, 1);
lcd.print("Humidity: ");
lcd.print(humidity);
lcd.print(" %");
// Wait a few seconds between measurements
delay(2000);
}