#include <LiquidCrystal.h>

// Initialize the LCD library with the numbers of the interface pins
LiquidCrystal lcd(8, 9, 10, 11, 12, 13);

// Define pins for ultrasonic sensor
const int trigPin = 6;
const int echoPin = 7;

// Define pins for LEDs
const int greenLedPin = 2;
const int yellowLedPin = 3;
const int redLedPin = 4;

// Define pin for buzzer
const int buzzerPin = 5;

// Variables for distance calculation
long duration;
int distance;

void setup() {
  // Initialize the LCD and set up the number of columns and rows
  lcd.begin(16, 2);
  lcd.print("Distance:");

  // Initialize serial communication
  Serial.begin(9600);
  
  // Set trigPin as an output and echoPin as an input
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  
  // Set LED pins as outputs
  pinMode(greenLedPin, OUTPUT);
  pinMode(yellowLedPin, OUTPUT);
  pinMode(redLedPin, OUTPUT);
  
  // Set buzzer pin as an output
  pinMode(buzzerPin, OUTPUT);
}

void loop() {
  // Clear the trigPin
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  
  // Send a pulse to trigger the sensor
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  
  // Measure the duration of the pulse received by the echoPin
  duration = pulseIn(echoPin, HIGH);
  
  // Calculate distance in centimeters
  distance = duration * 0.034 / 2;
  
  // Print the distance to the Serial Monitor and LCD
  Serial.print("Distance: ");
  Serial.print(distance);
  Serial.println(" cm");
  
  // Clear the previous distance from the LCD
  lcd.setCursor(0, 1);
  lcd.print("                ");
  lcd.setCursor(0, 1);
  lcd.print(distance);
  lcd.print(" cm");

  // Check distance level and control LEDs and buzzer accordingly
  if (distance < 20) {
    digitalWrite(greenLedPin, LOW);
    digitalWrite(yellowLedPin, LOW);
    digitalWrite(redLedPin, HIGH);
    tone(buzzerPin, 1000); // High frequency for close distance
    lcd.setCursor(0, 0);
    lcd.print("STOP           ");
    delay(100); // Short delay for fast beeping
    noTone(buzzerPin);
    delay(100); // Short delay between beeps
  } else if (distance >= 20 && distance < 50) {
    digitalWrite(greenLedPin, LOW);
    digitalWrite(yellowLedPin, HIGH);
    digitalWrite(redLedPin, LOW);
    tone(buzzerPin, 1000); // Medium frequency for medium distance
    lcd.setCursor(0, 0);
    lcd.print("CLOSE          ");
    delay(300); // Medium delay for medium beeping
    noTone(buzzerPin);
    delay(300); // Medium delay between beeps
  } else {
    digitalWrite(greenLedPin, HIGH);
    digitalWrite(yellowLedPin, LOW);
    digitalWrite(redLedPin, LOW);
    tone(buzzerPin, 1000); // Low frequency for far distance
    lcd.setCursor(0, 0);
    lcd.print("FREE           ");
    delay(500); // Long delay for slow beeping
    noTone(buzzerPin);
    delay(500); // Long delay between beeps
  }
}
$abcdeabcde151015202530354045505560fghijfghij