c - 如何设计一个断电安全的 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
}
}
解决方案
推荐阅读
- java - 为什么我的 JRE 位于 C:\Program Files (x86) 中,尽管它是 64 位版本?
- powershell - 使用 PIV 卡将网络共享中的文件夹重命名为其他用户的脚本
- kubectl - Kubectl 同时应用和设置镜像
- parsing - ANTLR4:如何识别字母表中的单词?
- netsuite - 从 UE 脚本的自定义记录中删除所有条目
- python-3.x - 无法使用子类的对象访问父类的全局变量
- amazon-web-services - 尝试使用 AWS tomcat CDI 创建命名查询时出现空异常
- html - 为什么 textarea 与输入文本的字体大小不同?
- python - Discord.py 机器人未检测到用户输入
- reactjs - 使用 Hooks 在 React 中重新渲染时停止/防止滚动到顶部(需要实现无限滚动)