来自blynk应用程序的Timewidget输入

时间:2018-08-04 07:37:55

标签: time arduino blynk

我正在使用blynk应用程序开发基于时间的应用程序。如果我的时间介于设定的时限之间,则必须打开继电器,否则必须关闭继电器。

我正在粘贴部分代码。在下面的代码中,如果我的时间设置在1小时范围内,它将起作用。如果时间> 2小时,它将无法正常工作。主要问题是比较时间小时和分钟。

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);
    }

  }

}

串行输出

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 个答案:

答案 0 :(得分:2)

比较午夜以来的秒数会更容易。如果您知道日期,甚至可以使用unix epoch,它是从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
}

如果时间有时可能是一整夜,则可以在下方插入类似内容以更改停止时间。例如:23:00至01:00变为23:00至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
}