Hi guys,
Currently, I am doing a mini project whereby I am using a PIR Motion control to control the state of my LED.
this is the PIR Motion sensor I am using : PIR motion sensor
How the program supposed to work is as follows: when a person passes by the motion sensor, the LED would turn on at 50% brightness the first two times. On the third pass by, the LED would turn on to max brightness. However, if during the first two times when the LED in on, after about 10seconds if there is no third output by the PIR Sensor, the LED would turn off.
int pir1 = 12;
int led3 = 5;
unsigned long ToppreviousMillis = 0;
unsigned long TopcurrentMillis;
void setup() {
// put your setup code here, to run once:
pinMode(pir1, INPUT);
pinMode(led3, OUTPUT);
Serial.begin(9600);
}
void loop() {
ToppreviousMillis = millis();
if (motiondetected()) { //if the PIR is detecting motion
analogWrite (led3, 50); //turn the light on
Serial.println("motion detected 1");
if (ToppreviousMillis > TopcurrentMillis + 10000) // if variable time is greater than variable time + 20 seconds
{
analogWrite (led3, 0); //turn the light back off
}
if (motiondetected()) {
analogWrite(led3, 50);
Serial.println("motion detected 2");
if (ToppreviousMillis > TopcurrentMillis + 10000) // if variable time is greater than variable time + 20 seconds
{
analogWrite (led3, 0); //turn the light back off
}
if (motiondetected()) {
analogWrite(led3, 255);
Serial.println("motion detected last");
}
}
}
}
bool motiondetected() {
if (digitalRead(pir1) == HIGH) {
TopcurrentMillis = millis();
return true;
} else {
return false;
}
}
However, my PIR Sensor would output HIGH several times for about 2seconds causing my if loops to activate over and over again. Could someone advice me on what's wrong with my code and point me in the right direction?
Thank you!