#include "DHT.h"
#include <LiquidCrystal_I2C.h>
#include <Wire.h>
#define DHTPIN 8 // Pin connected to the DHT sensor
#define DHTTYPE DHT22 // DHT 22 (AM2302)
LiquidCrystal_I2C lcd(0x27, 16, 2); // Initialize the LCD at I2C address 0x27 for a 16 chars and 2 line display
DHT dht(DHTPIN, DHTTYPE); // Initialize DHT sensor
float hum; // Stores humidity value
float temp; // Stores temperature value
void setup() {
Serial.begin(9600);
dht.begin(); // initialize the sensor
lcd.init(); // Initialize the lcd
lcd.backlight(); // Turn on the backlight
}
bool printedHeader = false; // Flag to check if header has been printed
void loop() {
hum = dht.readHumidity(); // Read humidity
temp = dht.readTemperature(); // Read temperature
// Check for failed sensor read and handle it
if (isnan(hum) || isnan(temp)) {
Serial.println("Failed to read from DHT sensor!");
}
else {
// Print to Serial Monitor
if (!printedHeader) {
Serial.println("Humidity,Temperature");
printedHeader = true;
}
Serial.print(hum);
Serial.print(",");
Serial.println(temp);
// Display on LCD
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Humid=");
lcd.print(hum);
lcd.print("%");
lcd.setCursor(0,1);
lcd.print("Temp=");
lcd.print(temp);
lcd.print(" C");
}
delay(2000); // Delay between reads
}