L151 RTC写入后读取异常,年份总是差几个数,有几点要注意:
1. weekday设成0
2. 网上有些文章说写要先日期,后时间,读取是先时间后日期,亲测无用,不过还是加上
3. 实测如果一条写指令后马上读会出错,延时1秒,正常
所以以上三点都加上,代码:
void setlocaltime(uint8_t *timestring){
RTC_DateTypeDef setDate;
RTC_TimeTypeDef setTime;
setDate.Year=char2num(timestring[0],timestring[1]);
setDate.Month=char2num(timestring[2],timestring[3]);
setDate.Date=char2num(timestring[4],timestring[5]);
setDate.WeekDay=0x00;
setTime.Hours=char2num(timestring[6],timestring[7]);
setTime.Minutes=char2num(timestring[8],timestring[9]);
setTime.Seconds=char2num(timestring[10],timestring[11]);
while(HAL_RTC_SetDate(&hrtc,&setDate,RTC_FORMAT_BIN)!= HAL_OK);
while(HAL_RTC_SetTime(&hrtc,&setTime,RTC_FORMAT_BCD)!= HAL_OK);
// debug the RTC write and read
// while(HAL_RTC_GetTime(&hrtc,&setTime,RTC_FORMAT_BCD)!= HAL_OK);
osDelay(1000);
while(HAL_RTC_GetDate(&hrtc,&setDate,RTC_FORMAT_BIN)!= HAL_OK);
}