// Define pins
const int trigPin = 2;  // Trigger pin of the ultrasonic sensor
const int echoPin = 3;  // Echo pin of the ultrasonic sensor
const int buzzerPin = 4;  // Digital pin to which the buzzer is connected

void setup() {
  Serial.begin(9600);  // Initialize serial communication for debugging
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(buzzerPin, OUTPUT);
}

void loop() {
  // Trigger ultrasonic sensor to send pulse
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  // Read the duration of the pulse from the echo pin
  long duration = pulseIn(echoPin, HIGH);

  // Calculate the distance in centimeters
  int distance = duration * 0.034 / 2;

  // Print the distance for debugging
  Serial.print("Distance: ");
  Serial.print(distance);
  Serial.println(" cm");

  // Check if the distance is too close (less than 20 cm)
  if (distance < 20) {
  // Turn on the buzzer
  tone(buzzerPin, 1000);  // 1000 Hz frequency
  } else {
  // Turn off the buzzer
  noTone(buzzerPin);
}


  // Delay before next reading
  delay(500);
}