// Define pin connections
#define TRIG_PIN 5
#define ECHO_PIN 18
#define BUZZER_PIN 23
void setup() {
//The setup initializes the sensor and buzzer pins.
pinMode(TRIG_PIN, OUTPUT); // Set the trigger pin as an output
pinMode(ECHO_PIN, INPUT); // Set the echo pin as an input
pinMode(BUZZER_PIN, OUTPUT); // Set buzzer pin as output
Serial.begin(115200); // Start serial communication
}
void loop() {
long duration, distance;
digitalWrite(TRIG_PIN, HIGH); // send a high trigger for 10 microseconds
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
duration = pulseIn(ECHO_PIN, HIGH); // read the echo signal to measure the return time.
distance = duration * 0.034 / 2; // calculate the distance in cm
Serial.print("Distance: ");
Serial.println(distance);
// Change beep duration based on distance
if (distance < 50 && distance > 0) { // Check for a valid distance reading
long beepDuration = map(distance, 0, 50, 50, 500); // Map distance to beep duration
tone(BUZZER_PIN, 1000, beepDuration); // Constant frequency of 1000 Hz, variable duration
delay(beepDuration + 200); // Wait for the beep to finish plus a short pause
} else {
noTone(BUZZER_PIN); // Turn off the buzzer if the distance is out of range
delay(500); // Longer pause when nothing is detected
}
}