使用HSE振荡器作为PLL的时钟源,并配置PLL作为系统时钟源系统时钟设置为168MHZ,写出相关代码
时间: 2024-10-14 09:06:52 浏览: 37
使用HSE(高频外部时钟源)作为PLL(锁相环路频率合成器)的输入并将其配置为系统的主时钟源,通常涉及嵌入式微控制器如STM32系列,这里我会给出一个基于STM32F4的示例代码片段。请注意,具体的代码会因硬件库的不同而有所差异,这里假设我们已经在项目中包含了`stm32f4xx_hal.h`等头文件。
```c
#include "stm32f4xx_hal.h"
// PLL Configuration Constants
#define HSE_VALUE 8000000 // Your HSE frequency (8 MHz in this example)
#define M_VALUE 8 // M value for the multiplication factor
#define N_VALUE 32768 // Prescaler value for system clock (HSI or HSI48)
#define PREDIV_VALUE 2 // PLL division factor
void SystemClock_Config(void) {
RCC_OscInitTypeDef RCC_OscInitStruct;
RCC_ClkInitTypeDef RCC_ClkInitStruct;
// Enable Power Control clock
__HAL_RCC_PWR_CLK_ENABLE();
// HSE configuration
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
RCC_OscInitStruct.HSEState = RCC_HSE_ON; // Enable HSE Oscillator
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; // Enable PLL
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE; // Use HSE as PLL input
RCC_OscInitStruct.PLL.PLLM = M_VALUE; // Set M (Multiplication Factor)
RCC_OscInitStruct.PLL.PLLN = N_VALUE; // Set N (Prescaler value for HSI or HSI48)
RCC_OscInitStruct.PLL.PLLP = PREDIV_VALUE; // Set PLLP (Division Factor)
RCC_OscInitStruct.PLL.PLLQ = 5; // Set Q (Clock Division)
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) {
Error_Handler(); // Handle error
}
// Select PLL as system clock source and set HSI prescaler
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; // HCLK at same speed as SYSCLK
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4; // PCLK1 divider
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2; // PCLK2 divider
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_5) != HAL_OK) {
Error_Handler();
}
// Output clock frequency check
uint32_t SysClockFreq = HAL_RCC_GetSysClockFreq();
if (SysClockFreq != 168000000) {
printf("Failed to set system clock to 16.8 MHz, current freq: %u MHz\n", SysClockFreq / 1000000);
}
}
int main(void) {
// ... (Your main function initialization here)
SystemClock_Config();
// ... (Continue with your main program)
}
阅读全文