Dusk/Dawn fading Led

Hi,

I wrote this simple code to fade led’s on in the morning and off at night.

#include <TimeLib.h>
#include <TimeAlarms.h>
#include <Wire.h>
#include <DS1307RTC.h>

int led = 3;

void setup()
{
  Serial.begin(9600);
  setSyncProvider(RTC.get);
  // create the alarms 
  Alarm.alarmRepeat(9,00,0, MorningAlarm); 
  Alarm.alarmRepeat(20,00,0,EveningAlarm);  
  for(int i=0;i<255; i++){
    analogWrite(led, i);
    delay(4700);
  }
  analogWrite(led, 255); 
}

void  loop(){  
  digitalClockDisplay();
  Alarm.delay(1000); 
}

void MorningAlarm(){
  for(int i=0;i<255; i++){
    analogWrite(led, i);
    delay(4700);
  }
  analogWrite(led, 255);   
}

void EveningAlarm(){
  for(int i=255;i>0; i--){
    analogWrite(led, i);
    delay(4700);
  }
  analogWrite(led, 0);      
}

void digitalClockDisplay()
{
  Serial.print(hour());
  printDigits(minute());
  printDigits(second());
  Serial.println(); 
}

void printDigits(int digits)
{
  Serial.print(":");
  if(digits < 10)
    Serial.print('0');
  Serial.print(digits);
}

It works ok, but I’m not entirely happy with it. I never want the led’s to just come on suddenly which is why I have the fade up code in setup as well. The problem is if the circuit is powered on between the night time alarm and morning alarm, the led’s will fade on when they should stay off.

Is there any way of making them fade on if power is added between the morning and night alarm, and stay off if power is added between the night and morning alarm?

Appreciate the help,

Damien.

In setup() you could check the current time - perhaps using elapsedSecsToday( now() ), to decide whether the LED should be on or off.

ozcar:
In setup() you could check the current time - perhaps using elapsedSecsToday( now() ), to decide whether the LED should be on or off.

ozcar, thank you. I added these lines of code which solved everything :slight_smile:

  if(elapsedSecsToday(now()) > 32400 && elapsedSecsToday(now()) < 72000){
    for(int i=0;i<255; i++){
      analogWrite(led, i);
      delay(4700);
    }
    analogWrite(led, 255); 
  }
  else{
    analogWrite(led, 0);
  }

Cheers