// Include the Ultrasonic sensor library
#include <Ultrasonic.h>
// Define pins for the Ultrasonic sensor
#define trigPin 9
#define echoPin 10
// Define pin for the alarm
#define alarmPin 8
// Define the distance threshold for triggering the alarm (in centimeters)
const int thresholdDistance = 50;
// Initialize the Ultrasonic sensor
Ultrasonic ultrasonic(trigPin, echoPin);
void setup() {
// Initialize serial communication for debugging
Serial.begin(9600);
// Set the alarm pin as an output
pinMode(alarmPin, OUTPUT);
}
void loop() {
// Measure the distance using the Ultrasonic sensor
int distance = ultrasonic.read();
// Print the distance to the serial monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Check if an object is within the threshold distance
if (distance < thresholdDistance) {
// If an object is detected, trigger the alarm
digitalWrite(alarmPin, HIGH);
Serial.println("Alarm triggered!");
} else {
// If no object is detected, turn off the alarm
digitalWrite(alarmPin, LOW);
}
// Delay for stability
delay(1000);
}