This time I have written a sketch to control a light with a PIR detector, well in this case the light is just a led. When the PIR detector detects movement it turns on the light, and after 30 seconds the light goes out. This is a common circuit in home automation, some of these PIR modules also have a clock so you can set the time for when it should work. There is no need to turn it on during the day when there is natural light. Since I have a DS1307 RTC module I thought why not try to make this myself.
I did not use the RTC library to get the time from the DS1307 but instead used code that I found here. With this code you can get the date and time from the DS1307, in the form of bytes over the I2C bus. The bytes are then converted to decimals so we can use them in our sketch. In this case we request the first 3 bytes, which are seconds, minutes and hours. In total you can request 7 bytes from the DS1307: second, minute, hour, day of the week, day of the month, month, year. I have made the sketch so that the PIR detector will turn on the the light after 18:00, and the light will turn off after 30 seconds.
The sketch:
/* http://www.bajdi.com PIR detector turns on light, light switches automatically off after 30 seconds. Light will only turn on in the evening (after 18:00) */ #include <Wire.h> const int DS1307_I2C_ADDRESS = 0x68; const int pir = 2; // the number of the PIR pin const int light = 13; // the number of the light pin unsigned long on; //start time for pir light on int pirState = 0; // variable for reading the pushbutton status byte second, minute, hour; // Convert binary coded decimal to normal decimal numbers byte bcdToDec(byte val) { return ( (val/16*10) + (val%16) ); } void getDateDs1307() { // Reset the register pointer Wire.beginTransmission(DS1307_I2C_ADDRESS); Wire.send(0x00); Wire.endTransmission(); Wire.requestFrom(DS1307_I2C_ADDRESS, 3); second = bcdToDec(Wire.receive() & 0x7f); minute = bcdToDec(Wire.receive()); hour = bcdToDec(Wire.receive() & 0x3f); // Need to change this if 12 hour am/pm } void setup() { Wire.begin(); pinMode(light, OUTPUT); pinMode(pir, INPUT); } void loop(){ getDateDs1307(); pirState = digitalRead(pir); if (pirState == HIGH && hour >= 18) { digitalWrite(light, HIGH); on = millis(); } unsigned long currentMillis = millis(); if ((currentMillis - on) > 30000) { digitalWrite(light, LOW); } }