# Automated Christmas Tree Lights

I’m having trouble writing the code to turn on my Christmas tree lights whenever a PIR sensor detects someone in the room. I want to have it so that if the lights are off and the sensor detects movement it turns on the lights for 20 minutes. I also want to make it so that if the sensor does not detect movement within those 20 minutes then the lights turn off after the 20 minutes; if the sensor does detect someone within the first 20 minutes then the lights stay on for an additional 20 minutes. So every time a person is detected the 20 minutes is renewed.

Right now the lights turn on when someone is detected and they stay on for 20 minutes, but turn off when that 20 minutes is over (no matter how many times the sensor detects someone in the first 20 minutes). Can you help me spot what’s going wrong here? Thanks!

``````int pCount = 0;       // Counts number of times sensor is activated
int count = 0;        // Counts 20 second time intervals

void setup()
{
pinMode(3, INPUT);      // Input to read if motion sensor is activated
pinMode(6, OUTPUT);     // Output to trigger relay to turn on lights
}

void loop()
{
if (digitalRead(3) == HIGH)  // Increases sensor counter is sensor is active
{
pCount++;
}
count++;                     // Increases time count only if sensor has been activated
delay(20000);                // 20 second delay to limit frequency program checks sensor status

if (pCount > 0)              // Checks to see if sensor has been activated
{
digitalWrite(6, HIGH);     // Turns on lights
if (count >= 60)           // IF statement at 20 minutes
{
count = 0;               // resets both counters after 20 minutes
if (pCount < 2)
{
digitalWrite(6,LOW);
pCount = 0;
}
else
{
pCount = 1;
}
}
}
}
``````

Generally use of delay is not good as you then block the program for doing further processing during the delay. If you instead use miliis() method to calculate the interval between trigger time and current time you will get around this. I rewrote your code to implement this. Worth to mention is that the code is written in notepad and without any testing so there could be some compilation errors.

``````#define PIR 6
#define OUT 3
#define ON_TIME 20 // in minutes

unsigned long movementDetected = 0;

void setup()
{
pinMode(PIR, INPUT);      // Input to read if motion sensor is activated
pinMode(OUT, OUTPUT);     // Output to trigger relay to turn on lights
}

void loop()
{