stm32G431HAL库修改RTC时间
时间: 2023-11-22 20:41:36 浏览: 119
以下是示例代码,用于将RTC时间设置为2022年1月1日1时1分1秒:
```
#include "stm32g4xx_hal.h"
#include "stm32g431xx.h"
#include "stm32g431xx_hal_rtc.h"
RTC_HandleTypeDef hrtc;
void SystemClock_Config(void);
int main(void)
{
HAL_Init();
SystemClock_Config();
__HAL_RCC_RTC_ENABLE();
hrtc.Instance = RTC;
hrtc.Init.HourFormat = RTC_HOURFORMAT_24;
hrtc.Init.AsynchPrediv = 127;
hrtc.Init.SynchPrediv = 255;
hrtc.Init.OutPut = RTC_OUTPUT_DISABLE;
hrtc.Init.OutPutPolarity = RTC_OUTPUT_POLARITY_HIGH;
hrtc.Init.OutPutType = RTC_OUTPUT_TYPE_OPENDRAIN;
if (HAL_RTC_Init(&hrtc) != HAL_OK)
{
Error_Handler();
}
RTC_TimeTypeDef sTime = {0};
sTime.Hours = 1;
sTime.Minutes = 1;
sTime.Seconds = 1;
if (HAL_RTC_SetTime(&hrtc, &sTime, RTC_FORMAT_BIN) != HAL_OK)
{
Error_Handler();
}
RTC_DateTypeDef sDate = {0};
sDate.Year = 22;
sDate.Month = RTC_MONTH_JANUARY;
sDate.Date = 1;
sDate.WeekDay = RTC_WEEKDAY_SATURDAY;
if (HAL_RTC_SetDate(&hrtc, &sDate, RTC_FORMAT_BIN) != HAL_OK)
{
Error_Handler();
}
while (1)
{
}
}
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct = {0};
RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI48;
RCC_OscInitStruct.HSI48State = RCC_HSI48_ON;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
{
Error_Handler();
}
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
|RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_HSI48;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_1) != HAL_OK)
{
Error_Handler();
}
}
```
在此代码中,我们首先启用RTC时钟,并初始化RTC句柄。然后,我们设置RTC时间和日期,最后进入无限循环。要修改时间和日期,请更改`sTime`和`sDate`结构中的字段。注意,`Year`字段是两位数,表示当前年份的后两位。在此示例中,我们将其设置为22,表示2022年。
阅读全文