Hi Guys,
I want to have a battery operated LED turn on when it gets dark, stay on a few hours, then off for 9 hours, the rest of the night, than wait for it to become dark again.
So LED to come on when light levels drop, stay on for a set time, then stay off for a set time regardless of light level and then wait until light levels drop.
My code works as I need except for on intial startup I need to wait for my one of my timers to expire and then it works as designed.
On a test rig with small timers this isn't a problem but when updated with a 9 hour "off time" it will annoy me. This is the problem I'm waiting for after startup. Even when condition one isnt met. I'm sure its simple but I cant nail it. I had 6 else ifs trying and it was just getting confusing.
else if ((sensorValue <= 400) && (ledState == LOW) && (currentMillis - previousMillis >= OffTime))
Full Code
#include <avr/sleep.h>
int ledPin = 0; // the number of the LED pin
int ledState = LOW; // ledState used to set the LED
unsigned long previousMillis = 0; // will store last time LED was updated
long OnTime = 5000; // milliseconds of on-time
long OffTime = 5000; // milliseconds of off-time
boolean On = 1;
int Power __attribute__ ((section (".noinit")));
void PowerDown () {
set_sleep_mode(SLEEP_MODE_PWR_DOWN);
ADCSRA &= ~(1<<ADEN); // Turn off ADC to save power
sleep_enable();
sleep_cpu();
}
void setup()
{
// set the digital pin as output:
pinMode(ledPin, OUTPUT);
Power = !Power;
if (!Power) PowerDown();
}
void loop()
{
int sensorValue = analogRead(3); //Read the sensor
// check to see if it's time to change the state of the LED
unsigned long currentMillis = millis();
if((ledState == HIGH) && (currentMillis - previousMillis >= OnTime))
{
ledState = LOW; // Turn it off
previousMillis = currentMillis; // Remember the time
digitalWrite(ledPin, ledState); // Update the actual LED
}
else if ((sensorValue <= 400) && (ledState == LOW) && (currentMillis - previousMillis >= OffTime))
{
ledState = HIGH; // turn it on
previousMillis = currentMillis; // Remember the time
digitalWrite(ledPin, ledState); // Update the actual LED
}
}