#define ECHO_PIN 2
#define TRIG_PIN 3
#define BUZZER_PIN 4
#define LED_PIN 13 // Assuming the built-in LED is connected to pin 13
#define DISTANCE_THRESHOLD 20
void setup() {
Serial.begin(115200);
pinMode(LED_PIN, OUTPUT);
pinMode(BUZZER_PIN, OUTPUT);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
}
float readDistanceCM() {
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
int duration = pulseIn(ECHO_PIN, HIGH);
return duration * 0.034 / 2;
}
void loop() {
float distance = readDistanceCM();
bool isNearby = distance < DISTANCE_THRESHOLD;
digitalWrite(LED_PIN, isNearby);
static bool wasNearby = false; // Variable to track previous state
if (isNearby) {
// Turn on the buzzer when an object is within the specified threshold distance
digitalWrite(BUZZER_PIN, HIGH);
wasNearby = true; // Update the previous state
} else if (wasNearby) {
// Turn off the buzzer if no object is detected within the threshold distance
digitalWrite(BUZZER_PIN, LOW);
wasNearby = false; // Update the previous state
}
Serial.print("Measured distance: ");
Serial.println(distance);
delay(100);
}