(一)STM32CubeMX设置
在上面的设置中,我在【Data Format】中使用的是RTC_FORMAT_BIN ,所有的年月日时分秒的格式都是十进制。
RTC_FORMAT_BIN 使用十进制 例如 18年你得到到是 18年
RTC_FORMAT_BCD 使用16进制 例如 18年你得到的是 0x18年
(二)代码
【rtc.c】
/* USER CODE BEGIN 0 */
RTC_TimeTypeDef GetTime; //RTC Time
RTC_DateTypeDef GetDate; //RTC Date
uint8_t RTC_READ_Flag;
/* USER CODE END 0 */
/*!
@Brief
Set the time of internal RTC
@Param
ucHour [Hour to set]
ucMinute [Minute to set]
ucSecond [Second to set]
@Return
null
*/
void RTC_SetTime(uint8_t ucHour, uint8_t ucMinute, uint8_t ucSecond)
{
/*Configure the Time*/
GetTime.Hours = ucHour;
GetTime.Minutes = ucMinute;
GetTime.Seconds = ucSecond;
// GetTime.TimeFormat = RTC_HOURFORMAT12_AM;
GetTime.DayLightSaving = RTC_DAYLIGHTSAVING_NONE;
GetTime.StoreOperation = RTC_STOREOPERATION_RESET;
if(HAL_RTC_SetTime(&hrtc, &GetTime, RTC_FORMAT_BIN) != HAL_OK)
{
Error_Handler();
}
}
/*!
@Brief
Set the date of internal RTC
@Param
ucYear [Year to set]
ucMonth [Month to set]
ucDay [Day to set]
@Return
null
*/
void RTC_SetDate(uint8_t ucYear, uint8_t ucMonth, uint8_t ucDay)
{
/*Configure the Date*/
GetDate.Year = ucYear;
GetDate.Month = ucMonth;
GetDate.Date = ucDay;
if (HAL_RTC_SetDate(&hrtc, &GetDate, RTC_FORMAT_BIN) != HAL_OK)
{
Error_Handler();
}
}
【rtc.h】
/* USER CODE BEGIN Prototypes */
/* Set the time of internal RTC */
void RTC_SetTime(uint8_t ucHour, uint8_t ucMinute, uint8_t ucSecond);
/* Set the date of internal RTC */
void RTC_SetDate(uint8_t ucYear, uint8_t ucMonth, uint8_t ucDay);
/* USER CODE END Prototypes */
【main.c】
/**Set the RTC time**/
RTC_SetTime(10, 5, 16); //set time 10:05:16
RTC_SetDate(21, 7, 15); //set date 2021-7-15
while (1)
{
//CANx_SendNormalData(&hcan1, CanID, Data, 5);
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
HAL_RTC_GetTime(&hrtc, &GetTime, RTC_FORMAT_BIN); //Get the time from the internal RTC
HAL_RTC_GetDate(&hrtc, &GetDate, RTC_FORMAT_BIN); //Get the date from the internal RTC
printf("20%d-%d-%d %d:%d:%d\r\n", GetDate.Year, GetDate.Month, GetDate.Date,
GetTime.Hours, GetTime.Minutes, GetTime.Seconds);
HAL_Delay(1000); //delay 1s
}
上面的HAL_RTC_GetTime要在HAL_RTC_GetDate之前调用,否则会有问题。