本人在调试stm32f051发现需要正确设置WeekDay才能显示正确年份。
代码主要从f4xx-hal的rtc驱动修改而来:
static rt_err_t rt_rtc_control(rt_device_t dev, int cmd, void args)
{
struct tm tm_now;
struct tm now;
RTC_TimeTypeDef sTime;
RTC_DateTypeDef sDate;
rt_enter_critical();
/* converts calendar time time into local time. */
tm_now = localtime((const time_t *)args);
/* copy the statically located variable */
memcpy(&now, tm_now, sizeof(struct tm));
/* unlock scheduler. */
rt_exit_critical();
switch (cmd)
{
case RT_DEVICE_CTRL_RTC_GET_TIME:
{
RTC_GetTime(RTC_Format_BIN, &sTime);
RTC_GetDate(RTC_Format_BIN, &sDate);
now.tm_hour = sTime.RTC_Hours;
now.tm_min = sTime.RTC_Minutes;
now.tm_sec = sTime.RTC_Seconds;
now.tm_year = sDate.RTC_Year + 100;
now.tm_mon = sDate.RTC_Month - 1;
now.tm_mday = sDate.RTC_Date;
*((time_t *)args) = mktime(&now);
}
break;
case RT_DEVICE_CTRL_RTC_SET_TIME:
{
sTime.RTC_Hours = now.tm_hour;
sTime.RTC_Minutes = now.tm_min;
sTime.RTC_Seconds = now.tm_sec;
RTC_SetTime(RTC_Format_BIN, &sTime);
sDate.RTC_Year = now.tm_year - 100;
sDate.RTC_Month = now.tm_mon + 1;
sDate.RTC_Date = now.tm_mday;
//notice weekday!
sDate.RTC_WeekDay = now.tm_wday + 1;
RTC_SetDate(RTC_Format_BIN, &sDate);
}
break;
}
return RT_EOK;
}