Skip to content

Instantly share code, notes, and snippets.

@OilSlick
Created January 6, 2017 09:37
Show Gist options
  • Save OilSlick/edc941bfa31406a59f74be8f32ea9cb6 to your computer and use it in GitHub Desktop.
Save OilSlick/edc941bfa31406a59f74be8f32ea9cb6 to your computer and use it in GitHub Desktop.
const int lightPin = 2; //PIN light sensor sensor is connected to. Pulls LOW with light
const int ledPin = 3; //PIN LED is connected to
const int pirPin = 4; //PIN PIR sensor is connected to
volatile unsigned long lastOnTime; //Record the time lights turned on
int long onDuration = 120000; //Time in millis to leave light on
int maxBrightness = 225; //Max Brightness of LEDs (used for battery preservation)
int fadeValue = 0; //Increments used for fading
void setup()
{
Serial.begin(9600);
pinMode(ledPin,OUTPUT);
digitalWrite(ledPin,LOW);
pinMode(pirPin,INPUT);
digitalWrite(pirPin,LOW);
pinMode(lightPin,INPUT);
digitalWrite(lightPin,LOW);
attachInterrupt(0, breakout, FALLING); //Break out on light detect
delay(1500); //Need delay to allow PIR sensor to settle
}
void loop()
{
if (digitalRead(lightPin) == HIGH)
{
if (digitalRead(pirPin)==HIGH)
{
if (Serial)
{
Serial.print("Light PIN: ");
Serial.println(digitalRead(lightPin));
Serial.println("Movement detected.");
}
fadein();
while (millis() <= (lastOnTime + onDuration) );
{
Serial.print("millis: ");
Serial.println(millis());
Serial.print("lastOnTime: ");
Serial.println(lastOnTime);
analogWrite(ledPin, maxBrightness);
}
lastOnTime = 0;
fadeout();
}
else
{
if (digitalRead(pirPin) == LOW)
{
lastOnTime = 0; //Reset
digitalWrite(ledPin,LOW);
if (Serial)
{
Serial.println("No movement detected.");
Serial.print("Light PIN: ");
Serial.println(digitalRead(lightPin));
}
}
}
}
}
void breakout()
{
lastOnTime = 1; //Reset
}
void fadein()
{
// fade in from min to max in increments of 3 points:
if (lastOnTime == 0) //Only fade once
{
lastOnTime = millis(); //Record the time lights turned on
for (int fadeValue = 0 ; fadeValue <= maxBrightness; fadeValue += 3)
{
// sets the value (range from 0 to 255):
analogWrite(ledPin, fadeValue);
// wait for 30 milliseconds to see the dimming effect
delay(30);
}
}
}
void fadeout()
{
// fade out from max to min in increments of 5 points:
for (int fadeValue = maxBrightness ; fadeValue >= 0; fadeValue -= 5)
{
// sets the value (range from 0 to 255):
analogWrite(ledPin, fadeValue);
// wait for 30 milliseconds to see the dimming effect
delay(30);
}
lastOnTime = 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment