// Define pins
const int trigPin = 2;
const int echoPin = 3;
const int buzzerPin = 4;
const int buttonPin = 5;
// Variables
long duration;
int distance;
bool buzzerState = false;
void setup() {
// Initialize pins
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(buzzerPin, OUTPUT);
pinMode(buttonPin, INPUT_PULLUP); // Use internal pull-up resistor
Serial.begin(9600);
}
void loop() {
// Send a pulse to the ultrasonic sensor
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the pulse from the ultrasonic sensor
duration = pulseIn(echoPin, HIGH);
distance = (duration / 2) / 29.1; // Calculate distance in cm
// Check if the button is pressed
if (digitalRead(buttonPin) == LOW) {
buzzerState = true; // Turn on buzzer if button is pressed
} else {
buzzerState = false; // Turn off buzzer if button is not pressed
}
// Control the buzzer
if (buzzerState && distance < 200) {
tone(buzzerPin, 1000); // Emit sound if object is within 20 cm and button is pressed
} else {
noTone(buzzerPin); // Turn off sound otherwise
}
// Print the distance to the Serial Monitor
//Serial.print("Distance: ");
//Serial.print(distance);
// Serial.println(" cm");
delay(100); // Delay for stability
}