Created
December 26, 2019 17:09
-
-
Save GreenMoonArt/695e44b360bc1b83c7bb89bc44cd6dd8 to your computer and use it in GitHub Desktop.
Light Sensor and Timing Control
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Use a LDR as a light sensor to turn on things (LEDs, motors, etc) when it gets dark. | |
* After a given time period, have them turn off (while it's still dark). | |
* Daylight resets the system as it waits for nightfall, to begin again. | |
*/ | |
unsigned long currentTime; | |
unsigned long loopTime; | |
unsigned long blinkTimer = (unsigned long)250; | |
// Need to cast each operand, otherwise the math is not correct: | |
unsigned long interval = (unsigned long)7 * (unsigned long)60 * (unsigned long)60 * (unsigned long)1000; // 7 hours | |
int darknessThreshold = 90; | |
byte blueLed = 5; | |
byte redLed = 11; | |
void setup() { | |
Serial.begin(9600); | |
pinMode(blueLed, OUTPUT); | |
pinMode(redLed, OUTPUT); | |
currentTime = millis(); | |
loopTime = currentTime; | |
} | |
void loop() { | |
int darknessValue = analogRead(A0); | |
Serial.println(darknessValue); | |
currentTime = millis(); | |
unsigned long myTimer = millis() % (unsigned long) 500; //timer for LED blinking | |
// interval = (unsigned long)5000; //for testing | |
if( darknessValue < darknessThreshold ) | |
// it is dark | |
{ | |
if( (unsigned long)(currentTime - loopTime) <= interval) | |
// we are have not reached the time limit | |
{ | |
// blink blue | |
if(myTimer < blinkTimer) | |
{digitalWrite(blueLed, HIGH);} | |
else | |
{digitalWrite(blueLed, LOW);} | |
digitalWrite(redLed, LOW); | |
} | |
else | |
// we have exceeded the time limit | |
{ | |
// blink red | |
if(myTimer < blinkTimer) | |
{digitalWrite(redLed, HIGH);} | |
else | |
{digitalWrite(redLed, LOW);} | |
digitalWrite(blueLed, LOW); | |
} | |
} | |
else | |
// it is daylight | |
{ | |
// reset timer, all LEDs off | |
loopTime = currentTime; | |
digitalWrite(blueLed, LOW); | |
digitalWrite(redLed, LOW); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment