// Define pin numbers for ultrasonic sensor
const int trigPin = 9;
const int echoPin = 10;
// Define pin numbers for buzzer and LED
const int buzzerPin = 8;
const int ledPin = 12;
// Variables to store duration and distance
long duration;
float distance;
const float thresholdDistance = 100.0; // Threshold in cm to trigger the alarm
void setup() {
// Set up Serial Monitor for debugging
Serial.begin(9600);
// Initialize ultrasonic sensor pins
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
// Initialize LED and buzzer pins
pinMode(buzzerPin, OUTPUT);
pinMode(ledPin, OUTPUT);
}
void loop() {
// Send a trigger pulse to the ultrasonic sensor
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echo pin and calculate the duration
duration = pulseIn(echoPin, HIGH);
// Calculate the distance in cm
distance = duration * 0.034 / 2;
// Print distance to the Serial Monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// If an object is within the threshold distance (person detected)
if (distance < thresholdDistance && distance > 0) {
// Turn on LED and buzzer
digitalWrite(ledPin, HIGH); // Turn ON LED
digitalWrite(buzzerPin, HIGH); // Turn ON buzzer
tone(buzzerPin, 31);
} else {
// Turn off LED and buzzer
digitalWrite(ledPin, LOW); // Turn OFF LED
digitalWrite(buzzerPin, LOW); // Turn OFF buzzer
noTone(buzzerPin);
}
// Delay before the next reading
delay(1000);
}