双击RT-Thread Setting,进入界面后点击更多配置。接着找到RTC驱动并勾选。
然后在drivers目录中打开board.h源文件,找到#define BSP_USING_ONCHIP_RTC的注释,取消掉。
修改drv_rtc.c文件,把
#ifndef HAL_RTCEx_BKUPRead
#define HAL_RTCEx_BKUPRead(x1, x2) (~BKUP_REG_DATA)
#endif
#ifndef HAL_RTCEx_BKUPWrite
#define HAL_RTCEx_BKUPWrite(x1, x2, x3)
#endif
注释掉,
修改下面的get_rtc_timestamp()函数如下
static time_t get_rtc_timestamp(void)
{
#if 0
RTC_TimeTypeDef RTC_TimeStruct = {0};
RTC_DateTypeDef RTC_DateStruct = {0};
struct tm tm_new;
HAL_RTC_GetTime(&RTC_Handler, &RTC_TimeStruct, RTC_FORMAT_BIN);
HAL_RTC_GetDate(&RTC_Handler, &RTC_DateStruct, RTC_FORMAT_BIN);
tm_new.tm_sec = RTC_TimeStruct.Seconds;
tm_new.tm_min = RTC_TimeStruct.Minutes;
tm_new.tm_hour = RTC_TimeStruct.Hours;
tm_new.tm_mday = RTC_DateStruct.Date;
tm_new.tm_mon = RTC_DateStruct.Month - 1;
tm_new.tm_year = RTC_DateStruct.Year + 100;
LOG_D("get rtc time.");
return mktime(&tm_new);
#else
time_t timestamp;
timestamp = RTC->CNTH;
/* 得到计数器中的值(秒钟数) */
timestamp <<= 16;
timestamp += RTC->CNTL;
LOG_D("get rtc time.");
return timestamp;
#endif
}
修改下面的set_rtc_time_stamp()函数如下:
static rt_err_t set_rtc_time_stamp(time_t time_stamp)
{
#if 0
RTC_TimeTypeDef RTC_TimeStruct = {0};
RTC_DateTypeDef RTC_DateStruct = {0};
struct tm *p_tm;
p_tm = localtime(&time_stamp);
if (p_tm->tm_year < 100)
{
return -RT_ERROR;
}
RTC_TimeStruct.Seconds = p_tm->tm_sec ;
RTC_TimeStruct.Minutes = p_tm->tm_min ;
RTC_TimeStruct.Hours = p_tm->tm_hour;
RTC_DateStruct.Date = p_tm->tm_mday;
RTC_DateStruct.Month = p_tm->tm_mon + 1 ;
RTC_DateStruct.Year = p_tm->tm_year - 100;
RTC_DateStruct.WeekDay = p_tm->tm_wday + 1;
if (HAL_RTC_SetTime(&RTC_Handler, &RTC_TimeStruct, RTC_FORMAT_BIN) != HAL_OK)
{
return -RT_ERROR;
}
if (HAL_RTC_SetDate(&RTC_Handler, &RTC_DateStruct, RTC_FORMAT_BIN) != HAL_OK)
{
return -RT_ERROR;
}
LOG_D("set rtc time.");
HAL_RTCEx_BKUPWrite(&RTC_Handler, RTC_BKP_DR1, BKUP_REG_DATA);
return RT_EOK;
}
#else
/* 设置时钟 */
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)));/* 等待RTC寄存器操作完成 */
HAL_RTCEx_BKUPWrite(&RTC_Handler, RTC_BKP_DR1, BKUP_REG_DATA);
LOG_D("set rtc time.");
return RT_EOK;
#endif
}
完成上述步骤后,打开终端msh命令输入date可以查到当前时间日期,一开始为默认时间,需要手动输入时间日期例如:
date 2021 06 23 16 56 30
进行设置。
原作者:巴菲特不非