Hello friends,
I need a little help with my home automation project. I would like to activate my light by opening the front door and to keep it on for a predetermined time. That would be fairly easy to accomplish with the delay function but I don't want to stop the entire sketch for, say, 20 seconds because I have more sensors and lights to control. What I need, and can't build myself, is a timer that starts when the door gets closed.
So it should work like: door open - lights go on (stay on), door closed - timer starts (light stays on until end of predetermined time).
I use servos to push the wall switches, and right now it only activates on door opening and outside lightlevel.
With delay the door part looks like this:
#include <Servo.h>
Servo myservo3;
int doorpin = 8; //door open switch
int lightstate = LOW;
int intervaltime = 10000;
int ldrpin = 0; //light dependent resistor
void setup(){
myservo3.attach(5);
pinMode(doorpin, INPUT);
pinMode(ldrpin, INPUT);
}
void loop()
{
if(analogRead(ldrpin) > 900) //over 900 means it's dark outside
{
if(digitalRead(doorpin) == LOW) //door open
{
if(lightstate == LOW) //light off
{
myservo3.write(126); //servo pushes lightswitch on
delay(500);
myservo3.write(90); //servo moves back to ready position
delay(500);
lightstate = HIGH; //light is on
delay(intervaltime); //waits specified interval
myservo3.write(59); //servo pushes lightswitch off
delay(500);
myservo3.write(90); //servo moves back to ready position
delay(500);
lightstate = LOW; //light is off
}
}
}
}
I tried different ideas but I probably have the wrong approach.
One of the not working idea I had looks like this:
#include <Servo.h>
Servo myservo3;
int doorpin = 8;
unsigned long currentdoortime;
unsigned long olddoortime = 0 ;
int doortimer = 5000;
int lightstate = LOW;
void setup(){
myservo3.attach(5);
pinMode(doorpin, INPUT);
}
void loop()
{
if(digitalRead(doorpin) == LOW) //door open
{
if(lightstate == LOW) //light off
{
myservo3.write(126); //servo pushes lightswitch on
delay(500);
myservo3.write(90); //servo moves back to ready position
delay(500);
lightstate = HIGH; //light on
}
else
{
if(lightstate == HIGH)
currentdoortime = millis(); //some not working timer idea,
if(currentdoortime - olddoortime > doortimer) //probably wrong approach
{
olddoortime = currentdoortime;
myservo3.write(59); //servo pushes lightswitch off
delay(500);
myservo3.write(90); //servo moves back to ready position
delay(500);
lightstate = LOW; //light off
}
}
}
}
But as you can see I try more and more confusing things that won't work.
It would be nice if you could point me in the right direction.
Thanks