const int PIR_PIN = 8;
const int BUZ_PIN = 7;
const int LED_PIN = 6;
const int BTN_PIN = 2;
bool isAlarm = false;
int oldPirState = 0;
int oldBtnState = 1; // pin idles HIGH with pullup
bool checkPIR() {
bool isTriggered = false;
int pirState = digitalRead(PIR_PIN); // read the pin
if (pirState != oldPirState) { // if it changed
oldPirState = pirState; // remember the state
if (pirState == HIGH) { // was just triggered
//Serial.println("Sensor triggered");
isTriggered = true;
} else { // just released
Serial.println("Sensor ready");
}
}
return isTriggered;
}
bool checkButton() {
bool wasPressed = false;
int btnState = digitalRead(BTN_PIN); // read the pin
if (btnState != oldBtnState) { // if it changed
oldBtnState = btnState; // remember the state
if (btnState == LOW) { // was just pressed
//Serial.println("Button Pressed");
wasPressed = true;
} else { // was just released
//Serial.println("Button Released");
}
delay(20); // short delay to debounce button
}
return wasPressed;
}
void setup() {
Serial.begin(115200);
pinMode(BTN_PIN, INPUT_PULLUP);
pinMode(PIR_PIN, INPUT);
pinMode(LED_PIN, OUTPUT);
}
void loop() {
// check sensor
if (checkPIR()) {
isAlarm = true;
tone(BUZ_PIN, 440);
digitalWrite(LED_PIN, HIGH);
Serial.print("Motion detected!\t");
Serial.println("Alarm On");
}
// check the button
if (checkButton() && isAlarm) {
isAlarm = false;
noTone(BUZ_PIN);
digitalWrite(LED_PIN, LOW);
Serial.print("Alarm canceled \t");
Serial.println("Alarm Off");
}
}