constexpr byte PIN_TO_SENSOR {3};
constexpr byte PIN_TO_BUZZER {9};
constexpr unsigned int RATE {500};
constexpr unsigned long FREQUENCY {1000000 / (RATE * 2)};
void setup() {
Serial.begin(9600);
pinMode(PIN_TO_SENSOR, INPUT);
pinMode(PIN_TO_BUZZER, OUTPUT);
Serial.println (FREQUENCY);
}
void loop() {
static bool isBuzzerOn {false};
static byte pinStatePrevious {LOW};
byte pinStateCurrent = digitalRead(PIN_TO_SENSOR);
if (HIGH == pinStateCurrent && false == isBuzzerOn) {
tone(PIN_TO_BUZZER, FREQUENCY);
isBuzzerOn = true;
Serial.println("Motion detected");
} else if (LOW == pinStateCurrent && true == isBuzzerOn) {
noTone(PIN_TO_BUZZER);
isBuzzerOn = false;
}
}
Click on the PIR sensor to trigger a motion detection.