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

// Define pins for LEDs
const int greenLedPin = 10;
const int yellowLedPin = 8;
const int redLedPin = 12;

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

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

void setup() {


  // 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);
  
  // Initialize the LCD and set up the number of columns and rows
  //lcd.begin(16, 2);
  //lcd.print("Distance: ");
}

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");
  
  //lcd.setCursor(0, 1);
  //lcd.print("                "); // Clear the previous distance
  //lcd.setCursor(10, 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
    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
    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
    delay(500); // Long delay for slow beeping
    noTone(buzzerPin);
   
    delay(500); // Long delay between beeps
  }
}