#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2); // I2C address 0x27, 16 columns and 2 rows
const int trigPin = 8; // Digital pin connected to the Trigger pin of the ultrasonic sensor
const int echoPin = 7; // Digital pin connected to the Echo pin of the ultrasonic sensor
const int buzzerPin = 6; // Digital pin connected to the buzzer
void setup() {
lcd.init(); // Initialize the LCD
lcd.backlight(); // Turn on the backlight
lcd.setCursor(0, 0); // Set cursor to the first column and first row
pinMode(trigPin, OUTPUT); // Set the Trig pin as an output
pinMode(echoPin, INPUT); // Set the Echo pin as an input
pinMode(buzzerPin, OUTPUT); // Set the buzzer pin as an output
}
void loop() {
// Measure the distance using the ultrasonic sensor
long duration, distance;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = duration * 0.034 / 2;
// Display distance on the LCD
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Distance: ");
lcd.print(distance);
lcd.print(" cm");
// Check distance and display messages on LCD, activate buzzer
if (distance >= 20) {
lcd.setCursor(0, 1);
lcd.print("Safe Distance");
noTone(buzzerPin);
} else if (distance < 20 && distance >= 15) {
lcd.setCursor(0, 1);
lcd.print("Be Careful");
tone(buzzerPin, 1000, 500);
} else if (distance < 15 && distance >= 8) {
lcd.setCursor(0, 1);
lcd.print("Distance NOT Safe");
tone(buzzerPin, 2000, 500);
} else {
lcd.setCursor(0, 1);
lcd.print("Too Close!");
tone(buzzerPin, 3000, 500);
}
delay(1000); // Delay for 1 second before taking the next measurement
}