#include "DHT.h"
#include <LiquidCrystal_I2C.h>
// Pin definitions
#define DHTPIN 4
#define DHTTYPE DHT22
// Initialize DHT sensor
DHT dht(DHTPIN, DHTTYPE);
// Initialize the LCD
LiquidCrystal_I2C lcd(0x27, 16, 2);
void setup() {
Serial.begin(9600); // Initialize serial communication for debugging
dht.begin(); // Initialize the DHT sensor
lcd.init(); // Initialize the LCD
lcd.backlight(); // Turn on the LCD backlight
}
void loop() {
// Read humidity and temperature
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.clear();
lcd.setCursor(0, 0);
lcd.print("Failed to read");
lcd.setCursor(0, 1);
lcd.print("from sensor!");
delay(3000);
return;
}
// Print sensor readings to serial monitor for debugging
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.print("%\tTemperature: ");
Serial.print(temperature);
Serial.println("C");
// Format the readings to 2 decimal places
char humStr[6];
dtostrf(humidity, 5, 2, humStr);
char tempStr[6];
dtostrf(temperature, 5, 2, tempStr);
// Display the results on the LCD
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Humidity=");
lcd.print(humStr);
lcd.print("%");
lcd.setCursor(0, 1);
lcd.print("Temp=");
lcd.print(tempStr);
lcd.print("C");
// Wait for 3 seconds before the next update
delay(3000);
}