#include <Arduino.h>
// Define the pin numbers for the ultrasonic sensor and buzzer
#define TRIGGER_PIN 7
#define ECHO_PIN 6
#define BUZZER_PIN 4
// Define the threshold distance for sounding the buzzer
#define BUZZER_DISTANCE_THRESHOLD 50 // Adjust as needed
// Function to initialize buzzer
void initBuzzer() {
pinMode(BUZZER_PIN, OUTPUT);
}
// Function to produce pulsing sound
void produceSound() {
// Sound the buzzer
tone(BUZZER_PIN, 1000); // 1000 Hz tone
delay(100); // Delay for 100 milliseconds
noTone(BUZZER_PIN); // Turn off the buzzer
}
void setup() {
// Initialize serial communication
Serial.begin(9600);
// Initialize ultrasonic sensor pins
pinMode(TRIGGER_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
// Initialize buzzer
initBuzzer();
}
void loop() {
// Trigger ultrasonic sensor to start measurement
digitalWrite(TRIGGER_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIGGER_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIGGER_PIN, LOW);
// Read the duration of the pulse from the echo pin
long duration = pulseIn(ECHO_PIN, HIGH);
// Convert the duration into distance (in centimeters)
// Speed of sound in air = 343 meters per second = 0.0343 cm/microsecond
float distance = duration * 0.0343 / 2;
// Print distance for debugging
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Check if the distance is less than the threshold
if (distance < BUZZER_DISTANCE_THRESHOLD) {
// If so, sound the buzzer
produceSound();
Serial.println("Object too close! Beep beep.");
}
// Delay before next sensor reading
delay(200); // Adjust as needed
}