// Define the pins to which the ultrasonic sensor is connected
int trigPin = 2;
int echoPin = 3;
// Define the pin to which the buzzer is connected
int buzzerPin = 4;
// Variable to store the distance measured by the ultrasonic sensor
long distance;
void setup() {
// Set the trigPin as an OUTPUT
pinMode(trigPin, OUTPUT);
// Set the echoPin as an INPUT
pinMode(echoPin, INPUT);
// Set the buzzerPin as an OUTPUT
pinMode(buzzerPin, OUTPUT);
// Start serial communication for debugging
Serial.begin(9600);
}
void loop() {
// Trigger the ultrasonic sensor to send a pulse
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Measure the time it takes for the pulse to return
distance = pulseIn(echoPin, HIGH) * 0.034 / 2;
// Print the distance to the serial monitor for debugging
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Check if the distance is less than a threshold (e.g., 50 cm) to activate the alarm
if (distance < 50) {
Serial.println("Intruder detected! Activating alarm!");
// Activate the alarm by turning on the buzzer
digitalWrite(buzzerPin, HIGH);
delay(1000); // Delay for 1 second
// Turn off the buzzer
digitalWrite(buzzerPin, LOW);
}
// Delay before the next measurement
delay(1000);
}