I am trying to make a security system using a motion sensor in Arduino. I almost have everything working the way I want it to, but I cannot figure out how to make the buzzer go off immediately after 60 seconds have passed while the light is on.
The code should work like this: When the motion sensor detects someone, the light turns on. if the light is on for 60 seconds, then the buzzer is turned on. The buzzer will not turn off until a button is pressed, which restarts the code.
I can make the buzzer go off if the time is logged (recorded, if you will) anytime above 60 seconds while the light is on, but that doesn't trigger the buzzer until the motion detector doesn't detect anything for 10 straight seconds (which determines when the time is logged)
My code should look something like this, but I'm unsure of the right way to set up a timer:
if (detectedLED, HIGH)
{
Start timer // Start a timer
if ((timer >= 60000)&&(detectedLED, HIGH))
{
digitalWrite(BuzzerPin, HIGH); // Enable Buzzer
BuzzerOnState = true; // Enable Buzzer State
}
}
I think this is what you want.
unsigned long timer = 0;
bool flag = false;
void loop() {
if (detectedLED, HIGH) {
if (!flag) {
flag = true;
timer = millis();
}
if ((millis() - timer) >= 60000) {
digitalWrite(BuzzerPin, HIGH); // Enable Buzzer
BuzzerOnState = true; // Enable Buzzer State
}
} else {
flag = false;
}
}