Timewidget Input from blynk app

2k Views Asked by At

I am developing time based application using blynk app. if my timing is between set time limit relay must be on else relay must be off.

I am pasting part of my code . Here in below code if my time set within 1 hour range it will work . if time is > 2 hour range it wont work. Main problem is comparing time hour & minute.

void TimeZone1_Function()
{

  if (TimeZone1 == 1)
  {
    // call with timer every 30 seconds or so
    // Get RTC time
    sprintf(currentTime, "%02d:%02d:%02d", hour(), minute(), second());
    Serial.print("Current Time: ");
    Serial.println(currentTime);

    // Get Time Input Widget time
    sprintf(startTime, "%02d:%02d:%02d", SThour, STmin, STsec);
    Serial.print("Start Time: ");
    Serial.println(startTime);

    sprintf(stopTime, "%02d:%02d:%02d", SPhour, SPmin, SPsec);
    Serial.print("Stop Time: ");
    Serial.println(stopTime);

    if (hour() >= SThour &&  hour() <= SPhour)
    {
      if (minute() >= STmin && minute() <= SPmin)
      {
        Serial.println("RELAY IS ON");
        Serial.println("..........................");
        digitalWrite(D5, HIGH); // Turn ON built-in LED
        led22.on();
      }
      else
      {
        Serial.println("RELAY IS OFF"); Serial.println("..........................");
        digitalWrite(D5, LOW); // Turn ON built-in LED
        led22.off();

      }
    }

    else
    {
      led22.off(); digitalWrite(D5, LOW);
        Blynk.virtualWrite(V51, 0);
    }

  }

}

Serial Output

Time Zone1 is selected
Current Time: 09:02:55
Start Time: 08:40:00
Stop Time: 10:40:00
RELAY IS OFF
…
AUTO mode is selected
Current Time: 09:03:06
Current Time: 09:03:07
Start Time: 09:03:00
Stop Time: 09:59:00
RELAY IS ON
1

There are 1 best solutions below

3
On BEST ANSWER

It gets easier if you compare seconds since midnight. If you know the date you could even use unix epoch, which is seconds since 1970-01-01 00:00.

int current_seconds = hour()*60*60 + minute()*60 + second();
int start_seconds = SThour*60*60 + STmin*60 + STsec;
int stop_seconds = SPhour*60*60 + SPmin*60 + SPsec;

// Is current time between set time limits?
if(current_seconds >= start_seconds && current_seconds <= stop_seconds)
{
  // Your relay code
}

If the time can sometimes be overnight, you could insert something like below to change the stop time. Example: 23:00 to 01:00 becomes 23:00 to 25:00

// if requested on-time is overnight, e.g. 23:00 to 01:00
if (stop_seconds < start_seconds)
{
  stop_seconds += 24*60*60; // add a day
}