#include <Wire.h>
#include <LiquidCrystal_I2C.h>
const int trigPin = 9; // Pin for sensor, trig pin transmits signal to object
const int echoPin = 10; // Pin for sensor, echo pin receives the signal
const int ledPin = 13; // LED pin on Arduino
const int buzzerPin = 2; // Buzzer pin on Arduino
long duration; // Distance variable
int distance;
const int safeDistance = 150; // Set the safe distance threshold
LiquidCrystal_I2C lcd(0x27, 16, 2); // Change the address if needed
void setup() {
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(ledPin, OUTPUT);
pinMode(buzzerPin, OUTPUT);
lcd.begin(16, 2); // Initialize the LCD
lcd.backlight(); // Turn on the LCD backlight
}
void loop() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH); // Trigger pin's output pulse
delayMicroseconds(10); // Short pulse for accuracy
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH); // Measure pulse duration
distance = duration * 0.034 / 2; // Calculate distance in cm
lcd.clear(); // Clear the LCD
lcd.setCursor(0, 0); // Set cursor to first line
lcd.print("Distance: ");
lcd.print(distance); // Print distance in cm
lcd.print(" cm");
if (distance <= 150 && distance >= 0) { // If distance is within range
digitalWrite(ledPin, HIGH); // Light LED
tone(buzzerPin, 500, 120); // Play tone
if (distance < safeDistance) { // If person is too close
lcd.setCursor(0, 1); // Set cursor to second line
lcd.print("Go back: ");
lcd.print(safeDistance - distance); // Distance to go back
lcd.print(" cm");
}
} else {
digitalWrite(ledPin, LOW); // Turn off LED
noTone(buzzerPin); // Stop buzzer sound
lcd.setCursor(0, 1);
lcd.print(" Safe Distance!"); // Clear previous message
}
delay(100); // Shorter delay for quicker response
}