STM32 通用定時(shí)器與滴答定時(shí)器
- 前言:STM32包括TIM1/TIM8兩個(gè)高級(jí)定時(shí)器,TIM2~TIM5四個(gè)通用定時(shí)器,TIM6/TIM7兩個(gè)基本定時(shí)器,還有使用非常方便的系統(tǒng)滴答定時(shí)器(systick),基本操作為:配置(使能時(shí)鐘/設(shè)置工作方式及初值/配置中斷/開啟中斷和時(shí)鐘/使能定時(shí)器)——>計(jì)數(shù)——>產(chǎn)生中斷。
一、通用定時(shí)器使用
void TimerConfig(void){TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;// 使能時(shí)鐘/復(fù)位/自動(dòng)重裝載設(shè)置/時(shí)鐘預(yù)分頻設(shè)置/采樣分頻/up/清除中斷/開啟時(shí)鐘RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2,ENABLE);TIM_DeInit(TIM2); TIM_TimeBaseStructure.TIM_Period = 2000 - 1;TIM_TimeBaseStructure.TIM_Prescaler = (36000 - 1);TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;TIM_TimeBaseInit(TIM2,&TIM_TimeBaseStructure);TIM_ClearFlag(TIM2,TIM_FLAG_Update);TIM_ITConfig(TIM2,TIM_IT_Update,ENABLE);TIM_Cmd(TIM2,ENABLE);// 中斷設(shè)置(組1/通道2/搶占式中斷優(yōu)先級(jí)0/響應(yīng)式中斷優(yōu)先級(jí)0/使能中斷)NVIC_InitTypeDef NVIC_InitStructure;NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQn;NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;NVIC_Init(&NVIC_InitStructure);}void TIM2_IRQHandler(void){if(TIM_GetITStatus(TIM2, TIM_IT_Update) != RESET){// 清除中斷標(biāo)志TIM_ClearITPendingBit(TIM2, TIM_FLAG_Update);timer_flag++;}}二、滴答定時(shí)器
void SysTmerConfig(void){if (SysTick_Config(SystemCoreClock / CLOCK_SECOND)){while (1);}}void SysTick_Handler(void){sys_timer_flag++;}
評(píng)論