RT-Thread ——RTC配置
STM32F103系列芯片的RTC功能存在一些缺陷。
一、显示时间戳
RTC(Real-Time Clock)译为实时时钟,因为它一般是集成电路,故也称为时钟芯片。它能提供精确的实时时间,可以用于产生年、月、日、时、分、秒等信息。
官方RTC讲解:RTC设备 (rt-thread.org)
步骤:
- 首先,我们在drivers目录中打开
board.h
源文件,找到RTC相关内容如下,并且将宏定义注释去掉:
-
在RT-Thread Setting中、将RTC进行详细配置,根据自己需求,配置RTC alarm和软件模拟RTC设备
-
在drivers目录下的
stm32xxxhal_config.h
文件中去掉如下代码的注释。此时可以根据FinSH命令进行时间的查看:
设置你的日期与时间:
-
二、解决复位日期不保存问题
通过以上操作发现所设置的时间与日期只是在那时设置成功,但下次下代码之后发现时间并不是所设置的。
原帖地址:RT-Thread-芯片掉电,只有rtc电源,rtthread读取年月日都为0,时分秒正常RT-Thread问答社区 - RT-Thread
解决操作:
-
打开
drivers
目录下的drv_rtc.c
文件 -
修改
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 }
3.修改
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 }
问题解决