STM32學(xué)習(xí)筆記(4):通用定時(shí)器基本定時(shí)功能
//使能預(yù)取指緩存
FLASH_PrefetchBufferCmd(FLASH_PrefetchBuffer_Enable);
//設(shè)置PLL時(shí)鐘,為HSE的9倍頻8MHz * 9 = 72MHz
RCC_PLLConfig(RCC_PLLSource_HSE_Div1, RCC_PLLMul_9);
//使能PLL
RCC_PLLCmd(ENABLE);
//等待PLL準(zhǔn)備就緒
while(RCC_GetFlagStatus(RCC_FLAG_PLLRDY) == RESET);
//設(shè)置PLL為系統(tǒng)時(shí)鐘源
RCC_SYSCLKConfig(RCC_SYSCLKSource_PLLCLK);
//判斷PLL是否是系統(tǒng)時(shí)鐘
while(RCC_GetSYSCLKSource() != 0x08);
}
//允許TIM2的時(shí)鐘
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2,ENABLE);
//允許GPIO的時(shí)鐘
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB,ENABLE);
}
void TIMER_cfg()
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
//重新將Timer設(shè)置為缺省值
TIM_DeInit(TIM2);
//采用內(nèi)部時(shí)鐘給TIM2提供時(shí)鐘源
TIM_InternalClockConfig(TIM2);
//預(yù)分頻系數(shù)為36000-1,這樣計(jì)數(shù)器時(shí)鐘為72MHz/36000 = 2kHz
TIM_TimeBaseStructure.TIM_Prescaler = 36000 - 1;
//設(shè)置時(shí)鐘分割
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
//設(shè)置計(jì)數(shù)器模式為向上計(jì)數(shù)模式
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
//設(shè)置計(jì)數(shù)溢出大小,每計(jì)2000個(gè)數(shù)就產(chǎn)生一個(gè)更新事件
TIM_TimeBaseStructure.TIM_Period = 2000 - 1;
//將配置應(yīng)用到TIM2中
TIM_TimeBaseInit(TIM2,&TIM_TimeBaseStructure);
//清除溢出中斷標(biāo)志
TIM_ClearFlag(TIM2, TIM_FLAG_Update);
//禁止ARR預(yù)裝載緩沖器
TIM_ARRPreloadConfig(TIM2, DISABLE);
//開(kāi)啟TIM2的中斷
TIM_ITConfig(TIM2,TIM_IT_Update,ENABLE);
}
void NVIC_cfg()
{
NVIC_InitTypeDef NVIC_InitStructure;
//選擇中斷分組1
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);
//選擇TIM2的中斷通道
NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQChannel;
//搶占式中斷優(yōu)先級(jí)設(shè)置為0
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
//響應(yīng)式中斷優(yōu)先級(jí)設(shè)置為0
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
//使能中斷
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
}
void GPIO_cfg()
{
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5;//選擇引腳5
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; //輸出頻率最大50MHz
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; //帶上拉電阻輸出
GPIO_Init(GPIOB,&GPIO_InitStructure);
}
在stm32f10x_it.c中,我們找到函數(shù)TIM2_IRQHandler(),并向其中添加代碼
void TIM2_IRQHandler(void)
{
u8 ReadValue;
//檢測(cè)是否發(fā)生溢出更新事件
if(TIM_GetITStatus(TIM2, TIM_IT_Update) != RESET)
{
//清除TIM2的中斷待處理位
TIM_ClearITPendingBit(TIM2 , TIM_FLAG_Update);
//將PB.5管腳輸出數(shù)值寫(xiě)入ReadValue
ReadValue = GPIO_ReadOutputDataBit(GPIOB,GPIO_Pin_5);
if(ReadValue == 0)
{
GPIO_SetBits(GPIOB,GPIO_Pin_5);
}
else
{
GPIO_ResetBits(GPIOB,GPIO_Pin_5);
}
}
}
評(píng)論