头文件
#ifndef APP_BSP_RCC_H
#define APP_BSP_RCC_H
#include "bsp_include.h"
void bsp_SystemClock_Conf(bool enable_hse, bool enable_lsi);
void bsp_SystemClock_PLL_Conf(bool enable_hse, bool enable_lsi);
#endif
源文件
#include "bsp_rcc.h"
void bsp_SystemClock_Conf(bool enable_hse, bool enable_lsi) {
RCC_OscInitTypeDef rcc_os = {0};
if (enable_hse) {
rcc_os.OscillatorType = RCC_OSCILLATORTYPE_HSE;
rcc_os.HSEState = RCC_HSE_ON;
} else {
rcc_os.OscillatorType = RCC_OSCILLATORTYPE_HSI;
rcc_os.HSIState = RCC_HSI_ON;
rcc_os.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
}
rcc_os.PLL.PLLState = RCC_PLL_NONE;
if (enable_lsi) {
rcc_os.OscillatorType |= RCC_OSCILLATORTYPE_LSI;
rcc_os.LSIState = RCC_LSI_ON;
}
if (HAL_RCC_OscConfig(&rcc_os) != HAL_OK) {
error_handle();
}
RCC_ClkInitTypeDef rcc_bus = {0};
rcc_bus.ClockType = RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2;
rcc_bus.SYSCLKSource = RCC_SYSCLKSOURCE_HSE;
rcc_bus.AHBCLKDivider = RCC_SYSCLK_DIV1;
rcc_bus.APB1CLKDivider = RCC_HCLK_DIV2;
rcc_bus.APB2CLKDivider = RCC_HCLK_DIV1;
if (HAL_RCC_ClockConfig(&rcc_bus, FLASH_LATENCY_0) != HAL_OK) {
error_handle();
}
}
void bsp_SystemClock_PLL_Conf(bool enable_hse, bool enable_lsi) {
RCC_OscInitTypeDef rcc_os = {0};
rcc_os.HSIState = RCC_HSI_ON;
if (enable_hse) {
rcc_os.OscillatorType = RCC_OSCILLATORTYPE_HSE;
rcc_os.HSEState = RCC_HSE_ON;
rcc_os.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
rcc_os.PLL.PLLState = RCC_PLL_ON;
rcc_os.PLL.PLLSource = RCC_PLLSOURCE_HSE;
rcc_os.PLL.PLLMUL = RCC_PLL_MUL9;
} else {
rcc_os.OscillatorType = RCC_OSCILLATORTYPE_HSI;
rcc_os.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
rcc_os.PLL.PLLState = RCC_PLL_ON;
rcc_os.PLL.PLLSource = RCC_PLLSOURCE_HSI_DIV2;
rcc_os.PLL.PLLMUL = RCC_PLL_MUL16;
}
if (enable_lsi) {
rcc_os.OscillatorType |= RCC_OSCILLATORTYPE_LSI;
rcc_os.LSIState = RCC_LSI_ON;
}
if (HAL_RCC_OscConfig(&rcc_os) != HAL_OK) {
error_handle();
}
RCC_ClkInitTypeDef rcc_bus = {0};
rcc_bus.ClockType = RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2;
rcc_bus.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
rcc_bus.AHBCLKDivider = RCC_SYSCLK_DIV1;
rcc_bus.APB1CLKDivider = RCC_HCLK_DIV2;
rcc_bus.APB2CLKDivider = RCC_HCLK_DIV1;
if (HAL_RCC_ClockConfig(&rcc_bus, FLASH_LATENCY_2) != HAL_OK) {
error_handle();
}
}