首页 > 解决方案 > 如何设计一个断电安全的 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
  }

}

标签: carduinomicrocontrollerarduino-c++real-time-clock

解决方案


推荐阅读