概述
实际使用STM32F103单片机时,第一步就是配置系统的工作时钟。我们时常需要选择使用外部时钟源和内部时钟源,这里我们以F103为例子,提供两个函数参考,供大家实际开发中使用配置系统时钟。
实例
废话不多说,直接上代码。
#include "dri_sysclk.h"
static void SetSystemClk(eSelectClkSrc _ClkSrc);
T_SysClk_Device g_tSysClk_Dev = {
.SysClkConfig = SetSystemClk
};
static void SetSysClockTo64(void)
{
__IO ErrorStatus HSIStartUpStatus = 0;
RCC_DeInit();
RCC_HSICmd(ENABLE);
if((RCC->CR & RCC_CR_HSIRDY) == RCC_CR_HSIRDY)
HSIStartUpStatus = SUCCESS;
else
HSIStartUpStatus = ERROR;
if(HSIStartUpStatus == SUCCESS)
{
FLASH_PrefetchBufferCmd(FLASH_PrefetchBuffer_Enable);
FLASH_SetLatency(FLASH_Latency_2);
RCC_HCLKConfig(RCC_SYSCLK_Div1);
RCC_PCLK2Config(RCC_HCLK_Div1);
RCC_PCLK1Config(RCC_HCLK_Div2);
RCC_PLLConfig(RCC_PLLSource_HSI_Div2, RCC_PLLMul_16);
RCC_PLLCmd(ENABLE);
while (RCC_GetFlagStatus(RCC_FLAG_PLLRDY) == RESET)
{
}
RCC_SYSCLKConfig(RCC_SYSCLKSource_PLLCLK);
while(RCC_GetSYSCLKSource() != 0x08)
{
}
}
else
{
while (1)
{
}
}
}
static void SetSysClockTo72(void)
{
__IO ErrorStatus HSEStartUpStatus = ERROR;
RCC_DeInit();
RCC_HSEConfig(RCC_HSE_ON);
HSEStartUpStatus = RCC_WaitForHSEStartUp();
if (HSEStartUpStatus == SUCCESS)
{
FLASH_PrefetchBufferCmd(FLASH_PrefetchBuffer_Enable);
FLASH_SetLatency(FLASH_Latency_2);
RCC_HCLKConfig(RCC_SYSCLK_Div1);
RCC_PCLK2Config(RCC_HCLK_Div1);
RCC_PCLK1Config(RCC_HCLK_Div2);
RCC_PLLConfig(RCC_PLLSource_HSE_Div1, RCC_PLLMul_9);
RCC_PLLCmd(ENABLE);
while (RCC_GetFlagStatus(RCC_FLAG_PLLRDY) == RESET)
{
}
RCC_SYSCLKConfig(RCC_SYSCLKSource_PLLCLK);
while(RCC_GetSYSCLKSource() != 0x08)
{
}
}
else
{
while (1)
{
}
}
}
static void SetSystemClk(eSelectClkSrc _ClkSrc)
{
switch(_ClkSrc)
{
case USE_HSE_FOR_CLKSRC:
SetSysClockTo72();
break;
case USE_HSI_FOR_CLKSRC:
SetSysClockTo64();
break;
default:
break;
}
RCC_ClockSecuritySystemCmd(ENABLE);
}
结论
通过上述配置,我们就可以成功配置系统时钟。
|