Turning on light from 6pm to 6am using ds3231

badly need help on this one

You need an extra variable that keeps track if the light is on or off.

bool lights;      // true when lights are on, false if lights are off.

void loop()
{
  ...

  if(!lights and Hour == 18)      // 6 p.m. and lights are not on ?
  {
    digitalWrite(LED, HIGH);      // turn light on
    lights = true;                // remember that the lights are on
  } 
  else if(lights and Hour == 6)   // lights are on and it is 6 a.m. ?
  {
    digitalWrite(LED, LOW);
    lights = false;
  }

  ...
}   
1 Like

In your case, you don't need to know the minutes value.

You can avoid handling the crossover at midnight by looking when the light should be off - i.e if hours > 5 and hours < 18.

And rather than constant digitalWrites, use the idea suggested above.

1 Like

An extra boolean isn't need. The output pin state is the same as the boolean.

The state of the pin change once between 6 and 18 and once outside that time

  if(Hour >= 6 && Hour <= 18){
    if(digitalRead(LED)){
      digitalWrite(LED, LOW);
    }    
  }
  else if(!digitalRead(LED)){
    digitalWrite(LED, HIGH);
  }

Hour == 6 and Hour == 18

Is tricky code. If the application starts at 19h it does nothing for the whole night.

1 Like

i tried this one and it worked, thank you so muuuuuch

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.