/*
Project: PIR alarm with button
Description: Turns on a buzzer & LED when motion
is detected. Button cancels the alarm.
The PIR 'delayTime' is set to 1.
Creation date: 9/3/23
Author: AnonEngineering
jio Arduino Discord coding-help, 9/3/23
The 'state' or 'mode' the sketch is in.
0 : idle, waiting for the PIR sensor
1 : buzzing, waiting for the button
*/
const int PIR_PIN = 8;
const int BUZ_PIN = 7;
const int LED_PIN = 6;
const int BTN_PIN = 2;
int state;
void setup() {
Serial.begin(115200);
pinMode(BTN_PIN, INPUT_PULLUP);
pinMode(PIR_PIN, INPUT_PULLUP); // Some PIR sensors are open-collector
pinMode(BUZ_PIN, OUTPUT);
pinMode(LED_PIN, OUTPUT);
state = 0;
}
void loop() {
if (state == 0) {
// Check the PIR sensor
if (digitalRead(PIR_PIN)) { // turn everything on
tone(BUZ_PIN, 440);
digitalWrite(LED_PIN, HIGH);
Serial.print("Motion detected!\t");
Serial.println("Alarm ON");
state = 1;
}
} else { // here state must be 1...
// Check the button
if (!digitalRead(BTN_PIN) ) { // turn everything off
noTone(BUZ_PIN);
digitalWrite(LED_PIN, LOW);
Serial.print("Alarm cancelled \t");
Serial.println("Alarm OFF\n");
state = 0;
}
}
}