#define triggerPin 2 // Pin connected to the TRIGGER pin of the ultrasonic sensor
#define echoPin 4 // Pin connected to the ECHO pin of the ultrasonic sensor
#define buzzerPin 5 // Pin connected to the buzzer
int beepcount = 0 ; // variable to trak the number of beeps
void setup() {
pinMode(triggerPin, OUTPUT);// Initialize the TRIGGER pin as an output
pinMode(echoPin, INPUT); // Initialize the ECHO pin as an input
pinMode(buzzerPin, OUTPUT);// Initialize the buzzer pin as an output
}
void loop() {
// Generate trigger pulse
digitalWrite(triggerPin, LOW);
delayMicroseconds(2);
digitalWrite(triggerPin, HIGH);
delayMicroseconds(10);
digitalWrite(triggerPin, LOW);
// Measure the pulse from the echo pin
long duration = pulseIn(echoPin, HIGH);
// Convert the pulse duration to distance
int distance = duration * 0.0343 / 2; // we devide the speed by 2 because the sound has to travel forward and back
// If an object is detected within 100cm, activate the buzzer
if (distance < 100 && beepcount <2 ) {
tone(buzzerPin, 100, 100); // Generate a 100ms beep
delay(100); // Wait for 100ms
noTone(buzzerPin); // Turn off the buzzer
delay(100); // Wait for 100ms
beepcount++; //increment the beepcount
}
delay(1000); // Wait for 1000ms before the next reading
if (distance >=100){
beepcount=0;
//reset beepcount if no object is detected
}
}