如何设计掉电安全的RTC时间开关?

问题描述

我正在使用带有DS3231实时时钟的ESP32。系统应每天根据用户可编程时间(HH:MM)自动打开和关闭输出。开/关小时/分钟存储在闪存中,因此它们是非易失性的。另外,输出停留的持续时间是硬编码的。

我正在尝试开发一个每秒调用一次的功能,以检查是否应该根据DS3231 RTC提供的当前时间打开或关闭输出。如果断电,这应该可以防止出现异常行为。因此,例如,如果在开通间隔之间暂时断电,则应在重新接通电源后为剩余时间间隔再次设置输出

如何相对计算当前时间是否在接通时间间隔之间?

const int8_t light_ontime_h = 2; // Hour interval for how long the output should stay on
const int8_t light_ontime_m = 42; // Minute interval for how long the output should stay on
struct tm currenttime; // Current time is stored in here,refreshed somewhere else in the program from RTC
struct tm ontime; // Hours and minutes to turn on are stored in here. Values are loaded from NVS on each reboot or on change. So struct only holds valid HH:MM info,date etc. is invalid

// This is called each second
void checkTime() {
  struct tm offtime;

  offtime.tm_hour = ontime.tm_hour + light_ontime_h;
  offtime.tm_min = ontime.tm_min + light_ontime_m;

  // normalize time
  mktime(&offtime);

  // Does not work if power is lost and correct hour/min was missed
  if ((currenttime.tm_hour == ontime.tm_hour) && (currenttime.tm_min == ontime.tm_min)) {
    // Turn output on
  } 
  if ((currenttime.tm_hour == offtime.tm_hour) && (currenttime.tm_min == offtime.tm_min)) {
    // Turn output off
  }

}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)