/* WREBOTICS Security Alarm V1 1/26/2024 */
// Constants for pin assignments
const int LED_PIN = 7;
const int TRIGGER_PIN = 8;
const int ECHO_PIN = 9;
const int BUZZER_PIN = 11;
const int MAX_DISTANCE = 75; // Maximum distance to trigger alarm (in centimeters)
void setup() {
pinMode(BUZZER_PIN, OUTPUT);
pinMode(LED_PIN, OUTPUT);
pinMode(TRIGGER_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
Serial.begin(9600);
}
void loop() {
// Initiate the ultrasonic pulse
digitalWrite(TRIGGER_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIGGER_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIGGER_PIN, LOW);
// Measure the duration of the echo pulse
long duration = pulseIn(ECHO_PIN, HIGH);
int distance = duration * 0.034 / 2; // Calculate the distance
// Display the distance
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Check if the distance is within the 'movement detected' range
if (distance <= MAX_DISTANCE) {
digitalWrite(LED_PIN, HIGH); // Turn on LED
Serial.println("Movement Detected");
tone(BUZZER_PIN, 330); // Emit an alternating tone
delay(400);
tone(BUZZER_PIN, 250);
delay(400);
} else {
digitalWrite(LED_PIN, LOW); // Turn off LED
noTone(BUZZER_PIN); // Stop emitting tone
}
// Short delay before the next loop iteration
delay(50);
}