#include <LiquidCrystal_I2C.h>
#include <DHT.h>
#include <ESP32Servo.h>
// I2C address of LCD
#define LCD_I2C_ADDRESS 0x27
// Ultrasonic sensor pins
#define TRIG_PIN 4
#define ECHO_PIN 2
// Buzzer pin
#define BUZZER_PIN 15
// DHT22 sensor pin
#define DHT_PIN 18
// Servo motor pin
#define SERVO_PIN 27
// LCD object
LiquidCrystal_I2C lcd(LCD_I2C_ADDRESS, 16, 2);
// DHT object
DHT dht(DHT_PIN, DHT22);
// Servo object
Servo servoMotor;
void setup() {
// Initialize LCD
lcd.init();
lcd.backlight();
// Set trigger pin as output
pinMode(TRIG_PIN, OUTPUT);
// Set echo pin as input
pinMode(ECHO_PIN, INPUT);
// Set buzzer pin as output
pinMode(BUZZER_PIN, OUTPUT);
// Attach the servo object to the servo pin
servoMotor.attach(SERVO_PIN);
// Initialize DHT sensor
dht.begin();
}
void loop() {
// Generate 10-microsecond pulse to TRIG pin
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// Measure duration of pulse from ECHO pin
float duration_us = pulseIn(ECHO_PIN, HIGH);
// Calculate the distance
float distance_cm = 0.017 * duration_us;
// Read temperature and humidity from DHT22
float temperature = dht.readTemperature();
float humidity = dht.readHumidity();
// Clear LCD
lcd.clear();
// Print distance on the first line of LCD
lcd.setCursor(0, 0);
lcd.print("Distance:");
lcd.print(distance_cm);
lcd.print("cm");
// Print temperature and humidity on the second line of LCD with decimal format
lcd.setCursor(0, 1);
lcd.print("T:");
lcd.print(temperature, 1); // Display temperature with 1 decimal place
lcd.print((char)223);
lcd.print("C | H:");
lcd.print(humidity, 0); // Display humidity with 1 decimal place
lcd.print("%"); // Use "P" instead of "%"
// If the distance is less than a threshold, activate the buzzer and move the servo
if (distance_cm < 10) {
digitalWrite(BUZZER_PIN, HIGH); // Turn on the buzzer
servoMotor.write(90); // Rotate the servo to 90 degrees
} else {
digitalWrite(BUZZER_PIN, LOW); // Turn off the buzzer
servoMotor.write(0); // Rotate the servo to 0 degrees
}
// Delay for 200ms
delay(200);
}