#include<DHT.h>
#include<LiquidCrystal.h>
#define DHTPIN 2 // Digital pin connected to the DHT sensor
#define DHTTYPE DHT22 // DHT 22 (AM2302)
const int trigPin = 4; // Trigger pin of the HC-SR04
const int echoPin = 3; // Echo pin of the HC-SR04
long duration; // Variable to store the duration of sound wave travel
int distance; // Variable to store the calculated distance
DHT dht(DHTPIN, DHTTYPE);
// Initialize the LCD interface pins
LiquidCrystal lcd(12,11,10,9,8,7);
void setup() {
Serial.begin(9600);
Serial.println("DHT22 Sensor Test");
dht.begin();
// Set up the LCD's number of columns and rows:
lcd.begin(16, 2);
}
void loop() {
delay(2000);
float temperature = dht.readTemperature(); // Read temperature as Celsius
float humidity = dht.readHumidity(); // Read humidity
// Check if any reads failed and exit early (to try again)
if (isnan(temperature) || isnan(humidity)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Measure the duration of the echo pulse
duration = pulseIn(echoPin, HIGH);
// Calculate the distance in centimeters
distance = duration * 0.034 / 2;
// Print temperature and humidity on Serial Monitor
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.println(" °C");
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.println(" %");
// Display temperature and humidity on LCD
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Temp: ");
lcd.print(temperature);
lcd.print(" C");
lcd.setCursor(0, 1);
lcd.print("Distance: ");
lcd.print(distance);
lcd.print(" cm");
}