Turn pin LOW within selected time interval

Hi!

I’m having trouble visualizing how the code should work. I want the relayPin to become LOW if between the desired startTime and stopTime. It works fine as long as you put the starting hour as a lower integer than the stopping hour.

But say you want something to turn on between 23:00 to 01:00. The first if statement will not execute since "currentHour will be < startTime when it’s 00:00.

How would you make this code work?

Let me know if something needs clarification.

Thanks

Also, I’m aware that the else if statement could be replaced with a simple “else” statement, it’s just to clarify what should happen between different time ranges.

And it would work if you would use : if (current.hour = startTime) and if (current.hour = stopTime) to start and stop, but this would make it hard to change stuff while in the desired time interval. Say that you need to reset the arduino for some reason = the relayPin won’t turn on until the next time current.hour = startTime. This is just a small part of a bigger project, so having it turn LOW always if between a desired time range is very important.

void checkTimeConditions(int currentHour, int startTime, int stopTime) {

  if (currentHour >= startTime && currentHour < stopTime) {

    digitalWrite(relayPin, LOW);
    digitalWrite(notActivePin, HIGH);

  }


  else if (currentHour < startTime || currentHour >= stopTime) {

    digitalWrite(relayPin, HIGH);
    digitalWrite(notActivePin, LOW);

  }
}

Try this:

  if (startTime <= stopTime) {
    if (currentHour >= startTime && currentHour < stopTime) {

      digitalWrite(relayPin, LOW);
      digitalWrite(notActivePin, HIGH);

    }
  }
  else  { // stopTime < startTime
    if (!(currentHour >= startTime && currentHour < stopTime)) {

      digitalWrite(relayPin, LOW);
      digitalWrite(notActivePin, HIGH);

    }
  }

ziggyt: How would you make this code work?

I built a library (DailyTimer) just for this use case.

It allows you to bridge midnight...