STM32 通用定时器与滴答定时器
- 前语:STM32包含TIM1/TIM8两个府第定时器,TIM2~TIM5四个通用定时器,TIM6/TIM7两个根本定时器,还有运用十分便利的体系滴答定时器(systick),根本操作为:装备(使能时钟/设置工作方式及初值/装备中止/舱位中止和时钟/使能定时器)——>计数——>发生中止。
一、通用定时器运用
void TimerConfig(void){TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;// 使能时钟/复位/主动重装载设置/时钟预分频设置/采样分频/up/铲除中止/舱位时钟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);// 中止设置(组1/通道2/抢占式中止优先级0/呼应式中止优先级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){// 铲除中止标志TIM_ClearITPendingBit(TIM2, TIM_FLAG_Update);timer_flag++;}}
二、滴答定时器
void SysTmerConfig(void){if (SysTick_Config(SystemCoreClock / CLOCK_SECOND)){while (1);}}void SysTick_Handler(void){sys_timer_flag++;}