#define triggerPin 15 // 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
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 generateTriggerPulse() {
digitalWrite(triggerPin, LOW);
delayMicroseconds(2);
digitalWrite(triggerPin, HIGH);
delayMicroseconds(10);
digitalWrite(triggerPin, LOW);
}
long getEchoDuration() {
return pulseIn(echoPin, HIGH);
}
int convertToDistance(long duration) {
return duration * 0.0343 / 2;
}
void activateBuzzer() {
tone(buzzerPin, 1000, 1000); // Generate a 1000ms beep
delay(1000); // Wait for 1000ms
noTone(buzzerPin); // Turn off the buzzer
delay(100); // Wait for 100ms
}
void loop() {
generateTriggerPulse();
long duration = getEchoDuration();
int distance = convertToDistance(duration);
if (distance < 50) {
activateBuzzer();
}
delay(100);
}