const int trigPin = 14; // Pin for the ultrasonic sensor trigger
const int echoPin = 27; // Pin for the ultrasonic sensor echo
const int led = 15; // Pin for the LED
const int buzzer = 5; // Pin for the buzzer
void setup() {
Serial.begin(9600); // Initialize serial communication
pinMode(trigPin, OUTPUT); // Set trigger pin as output
pinMode(echoPin, INPUT); // Set echo pin as input
pinMode(led, OUTPUT); // Set LED pin as output
pinMode(buzzer, OUTPUT); // Set buzzer pin as output
}
void loop() {
// Send ultrasonic pulse
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Measure the echo duration
unsigned long duration = pulseIn(echoPin, HIGH);
// Calculate distance in centimeters
unsigned int distance = duration * 0.034 / 2;
if (distance > 0 && distance <= 100) { // If an object is detected within 100cm
// Display distance in the serial console
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Sound the buzzer and blink the LED
tone(buzzer, 250, 300); // Sound buzzer with frequency of 250 Hz for 300 ms
digitalWrite(led, HIGH); // Turn on the LED
delay(1000); // Delay for 1 second
digitalWrite(led, LOW); // Turn off the LED
} else {
Serial.println("No object detected!"); // Print message if no object detected
}
delay(500); // Wait for some time before the next measurement
}