STM32 HAL library development series - TIM timer interrupt

STM32 HAL library development series - TIM timer interrupt

NVIC configuration

 /**
 * @brief  基本定时器 TIMx,x[6,7]中断优先级配置
 * @param  无
 * @retval 无
 */
 static void TIMx_NVIC_Configuration(void)
 {
     //设置抢占优先级,子优先级
     HAL_NVIC_SetPriority(BASIC_TIM_IRQn, 0, 3);
     // 设置中断来源
     HAL_NVIC_EnableIRQ(BASIC_TIM_IRQn);
 }

The experiment uses the timer update interrupt, and needs to configure the NVIC.

Basic Timer Mode Configuration

The timer clock must be turned on before using the timer, and the basic timer belongs to the APB1 bus peripheral.

Next, set the number of timer cycles to 4999, that is, count 5000 generated events. Set the timer prescaler to (8400-1), the basic timer enables the internal clock, the frequency is 84MHz, and the frequency of 10KHz is obtained after the prescaler. Then call the TIM_HAL_TIM_Base_Init function to complete the timer configuration.

Finally, use the HAL_TIM_Base_Start_IT function to start the timer and update the interrupt.

 static void TIM_Mode_Config(void)
 {
     // 开启TIMx_CLK,x[6,7]
     BASIC_TIM_CLK_ENABLE();

     TIM_TimeBaseStructure.Instance = BASIC_TIM;
     /* 累计 TIM_Period个后产生一个更新或者中断*/
     //当定时器从0计数到4999,即为5000次,为一个定时周期
     TIM_TimeBaseStructure.Init.Period = 5000-1;
     //定时器时钟源TIMxCLK = 2 * PCLK1
     //        PCLK1 = HCLK / 4
     //        => TIMxCLK=HCLK/2=SystemCoreClock/2=84MHz
     // 设定定时器频率为=TIMxCLK/(TIM_Prescaler+1)=10000Hz
     TIM_TimeBaseStructure.Init.Prescaler = 8400-1;

     // 初始化定时器TIMx, x[2,3,4,5]
     HAL_TIM_Base_Init(&TIM_TimeBaseStructure);

     // 开启定时器更新中断
     HAL_TIM_Base_Start_IT(&TIM_TimeBaseStructure);
 }

Timer interrupt service function

 void  BASIC_TIM_IRQHandler (void)
 {
     HAL_TIM_IRQHandler(&TIM_TimeBaseStructure);
 }
 void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
 {
     if (htim==(&TIM_TimeBaseStructure)) {
         LED1_TOGGLE;  //红灯周期闪烁
     }
 }

References and citations: STM32F4xx Reference Manual, STM32F4xx Specification, Wildfire Open Source Project, Library Help Documentation

Guess you like

Origin blog.csdn.net/sorcererr/article/details/128698220