// Include libraries
#include <DHT.h> // DHT sensor library
#include <LiquidCrystal_I2C.h> // LCD library
#include <Wire.h> // Wire library for I2C communication
// Initialize LCD with address 0x27, 16 columns, and 2 rows
LiquidCrystal_I2C lcd(0x27, 16, 2);
// Constants for DHT sensor
#define DHTPIN A3 // Pin where DHT sensor data is connected
#define DHTTYPE DHT11 // DHT 11 sensor type
// Initialize DHT sensor
DHT dht(DHTPIN, DHTTYPE);
// Variables for humidity and temperature
int h; // Stores humidity value
int t; // Stores temperature value
void setup() {
// Start serial communication
Serial.begin(9600);
Serial.println("Temperature and Humidity Sensor Test");
// Initialize DHT sensor
dht.begin();
// Initialize LCD
lcd.begin(16, 2); // Set LCD size (16 characters and 2 rows)
lcd.backlight(); // Turn on LCD backlight
}
void loop() {
// Read humidity and temperature values from the sensor
h = dht.readHumidity();
t = dht.readTemperature();
// Check if reading was successful
if (isnan(h) || isnan(t)) {
Serial.println("Failed to read from DHT sensor");
return; // Exit the loop if reading failed
}
// Print the values to the serial monitor
Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %, Temp: ");
Serial.print(t);
Serial.println(" °C");
// Display the results on the LCD
lcd.clear(); // Clear the LCD screen
// Set cursor to the first line, first column
lcd.setCursor(0, 0);
lcd.print("Humidity: ");
lcd.print(h);
lcd.print("%");
// Set cursor to the second line, first column
lcd.setCursor(0, 1);
lcd.print("Temp: ");
lcd.print(t);
lcd.print("C");
// Delay for 1 second before taking the next reading
delay(1000);
}