STM32CubeMX系列教程13:实时时钟(RTC)
从操作函数中可以看到,时间和日期是以结构体的形式读写的。所以在main.c文件前面申明两个结构体变量存储读取的时间和日期数据。
/* USER CODE BEGIN PV */ /* Private variables ---------------------------------------------------------*/ RTC_DateTypeDef sdatestructure; RTC_TimeTypeDef stimestructure; /* USER CODE END PV */
在stm32f7xx_hal_rtc.h头文件中,可以找到RTC_TimeTypeDef,RTC_DateTypeDef这两个结构体的成员变量。
/**
* @brief RTC Time structure definition
*/
typedef struct
{
uint8_t Hours; /*!< Specifies the RTC Time Hour.
This parameter must be a number between Min_Data = 0 and Max_Data = 12
if the RTC_HourFormat_12 is selected.
This parameter must be a number between Min_Data = 0 and Max_Data = 23
if the RTC_HourFormat_24 is selected */
uint8_t Minutes; /*!< Specifies the RTC Time Minutes.
This parameter must be a number between Min_Data = 0 and Max_Data = 59 */
uint8_t Seconds; /*!< Specifies the RTC Time Seconds.
This parameter must be a number between Min_Data = 0 and Max_Data = 59 */
uint32_t SubSeconds; /*!< Specifies the RTC Time SubSeconds.
This parameter must be a number between Min_Data = 0 and Max_Data = 59 */
uint8_t TimeFormat; /*!< Specifies the RTC AM/PM Time.
This parameter can be a value of @ref RTC_AM_PM_Definitions */
uint32_t DayLightSaving; /*!< Specifies RTC_DayLightSaveOperation:
the value of hour adjustment.
This parameter can be a value of @ref RTC_DayLightSaving_Definitions */
uint32_t StoreOperation; /*!< Specifies RTC_StoreOperation value to be written in the BCK bit
in CR register to store the operation.
This parameter can be a value of @ref RTC_StoreOperation_Definitions*/
}RTC_TimeTypeDef;
/**
* @brief RTC Date structure definition
*/
typedef struct
{
uint8_t WeekDay; /*!< Specifies the RTC Date WeekDay.
This parameter can be a value of @ref RTC_WeekDay_Definitions */
uint8_t Month; /*!< Specifies the RTC Date Month (in BCD format).
This parameter can be a value of @ref RTC_Month_Date_Definitions */
uint8_t Date; /*!< Specifies the RTC Date.
This parameter must be a number between Min_Data = 1 and Max_Data = 31*/
uint8_t Year; /*!< Specifies the RTC Date Year.
This parameter must be a number between Min_Data = 0 and Max_Data = 99*/
}RTC_DateTypeDef;在while循环中添加应用程序,读取当前的时间和日期,并通过串口发送到电脑上显示。
/* USER CODE BEGIN WHILE */
while (1)
{
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
/* Get the RTC current Time ,must get time first*/
HAL_RTC_GetTime(&hrtc, &stimestructure, RTC_FORMAT_BIN);
/* Get the RTC current Date */
HAL_RTC_GetDate(&hrtc, &sdatestructure, RTC_FORMAT_BIN);
/* Display date Format : yy/mm/dd */
printf("%02d/%02d/%02d\r\n",2000 + sdatestructure.Year, sdatestructure.Month, sdatestructure.Date);
/* Display time Format : hh:mm:ss */
printf("%02d:%02d:%02d\r\n",stimestructure.Hours, stimestructure.Minutes, stimestructure.Seconds);
printf("\r\n");
HAL_Delay(1000);
}
/* USER CODE END 3 */程序中使用HAL_RTC_GetTime(),HAL_RTC_GetDate()读取时间和日期,并保存到结构体变量中,然后通过串口输出读取的时间和日期。注意:要先读取时间再读取日期,如果先读取日期在读取时间会导致读取的时间不准确,一直都是原来设置的时间。









支付宝打赏
微信打赏 


