#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2); // I2C address 0x27, 16 columns, 2 rows
#define TRIG_PIN 23 // ESP32 pin GPIO23 connected to Ultrasonic Sensor's TRIG pin
#define ECHO_PIN 19 // ESP32 pin GPIO19 connected to Ultrasonic Sensor's ECHO pin
#define BUZZER_PIN 18 // ESP32 pin GPIO18 connected to Buzzer
float duration_us, distance_cm;
void setup() {
lcd.init(); // initialize the lcd
lcd.backlight(); // turn on the backlight
pinMode(TRIG_PIN, OUTPUT); // set TRIG pin as output
pinMode(ECHO_PIN, INPUT); // set ECHO pin as input
pinMode(BUZZER_PIN, OUTPUT); // set BUZZER pin as output
}
void loop() {
// generate a 10-microsecond pulse to TRIG pin
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// measure duration of pulse from ECHO pin
duration_us = pulseIn(ECHO_PIN, HIGH);
// calculate the distance in cm
distance_cm = 0.017 * duration_us;
lcd.clear();
lcd.setCursor(0, 0); // start printing at the first row
lcd.print("Distance: ");
lcd.print(distance_cm);
// Activate the buzzer if the distance is less than a certain threshold
if (distance_cm < 5) { // if object is within 10 cm
digitalWrite(BUZZER_PIN, HIGH); // turn on the buzzer
} else {
digitalWrite(BUZZER_PIN, LOW); // turn off the buzzer
}
delay(500); // wait for 500ms before next measurement
}