#define TRIG_PIN 17 // Trig pin of the ultrasonic sensor
#define ECHO_PIN 16 // Echo pin of the ultrasonic sensor
#define BUZZER_PIN 18 // Pin for the buzzer
void setup() {
// Start serial communication for debugging
Serial.begin(115200);
// Set pin modes for the ultrasonic sensor
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
// Set pin mode for the buzzer
pinMode(BUZZER_PIN, OUTPUT);
}
void loop() {
long duration, distance;
// Trigger the ultrasonic sensor
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// Read the echo pulse duration
duration = pulseIn(ECHO_PIN, HIGH);
// Calculate distance in cm
distance = duration * 0.034 / 2;
// Print the distance (for debugging)
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// If the distance is less than or equal to 12 cm, activate the buzzer
if (distance <= 12 && distance > 0) {
tone(BUZZER_PIN, 1000); // 1000 Hz tone
} else {
noTone(BUZZER_PIN); // Turn off the buzzer
}
// Wait for a short period before the next measurement
delay(500);
}