const int trigPin = 9; // Pin connected to the trigger pin of the ultrasonic sensor
const int echoPin = 10; // Pin connected to the echo pin of the ultrasonic sensor
const int buzzerPin = 7; // Pin connected to the positive terminal of the buzzer
const int ledPin = 13; // Pin connected to the LED
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(buzzerPin, OUTPUT);
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}
void loop() {
// Triggering the ultrasonic sensor
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reading the distance from the ultrasonic sensor
long duration = pulseIn(echoPin, HIGH);
int distance = duration * 0.034 / 2;
// Checking if an object is within a certain range (adjust as needed)
if (distance < 30) {
// Object detected, activate buzzer and LED
digitalWrite(buzzerPin, HIGH);
digitalWrite(ledPin, HIGH);
} else {
// No object detected, turn off buzzer and LED
digitalWrite(buzzerPin, LOW);
digitalWrite(ledPin, LOW);
}
// Print distance to serial monitor for testing (optional)
Serial.print("Distance: ");
Serial.println(distance);
// Add a delay to avoid rapid triggering
delay(500);
}