前言
STM32F1系列官方库没有保存年月日的功能,断电上电后会恢复初始值。所以根据RT-Thread官方例程操作后,年月日断电并不能保存。
硬件RTC的使用方法
1.CubeMX Settings中打开外部晶振并配置时钟源,打开RTC功能
2.首先需要打开RT-Thread Settings中RTC的驱动支持,但不要打开软件模拟RTC设备
3.drivers/board.h中打开硬件RTC的定义
RTC驱动修改
修改RTC驱动,实现断电保存年月日功能,这里参考了RT-Tread论坛中帖子的解决方案,原贴地址:https://club.rt-thread.org/ask/question/422537.html
修改drivers/drv_rtc.c的以下两个函数,改为RTC CNT直接存时间戳
static time_t get_rtc_timestamp(void)
{
time_t timestamp;
timestamp = RTC->CNTH;
timestamp <<= 16;
timestamp += RTC->CNTL;
LOG_D("get rtc time.");
return timestamp;
}
static rt_err_t set_rtc_time_stamp(time_t time_stamp)
{
RCC->APB1ENR |= 1<<28;
RCC->APB1ENR |= 1<<27;
PWR->CR |= 1 << 8;
RTC->CRL |= 1 << 4;
RTC->CNTL = time_stamp & 0xffff;
RTC->CNTH = time_stamp >> 16;
RTC->CRL &= ~(1 << 4);
while (!(RTC->CRL & (1 << 5)));
LOG_D("set rtc time.");
HAL_RTCEx_BKUPWrite(&RTC_Handler, RTC_BKP_DR1, BKUP_REG_DATA);
return RT_EOK;
}
例程
经过上述修改过程,完美解决了掉电后无法保存年月日的问题,可用如下官方例程测试。
#include <rtthread.h>
#include <rtdevice.h>
static int rtc_sample(int argc, char *argv[])
{
rt_err_t ret = RT_EOK;
time_t now;
ret = set_date(2022, 1, 2);
if (ret != RT_EOK)
{
rt_kprintf("set RTC date failed\n");
return ret;
}
ret = set_time(5, 50, 50);
if (ret != RT_EOK)
{
rt_kprintf("set RTC time failed\n");
return ret;
}
rt_thread_mdelay(3000);
now = time(RT_NULL);
rt_kprintf("%s\n", ctime(&now));
return ret;
}
MSH_CMD_EXPORT(rtc_sample, rtc sample);
|