stm32有很多定时器,每种定时器的功能也不尽相同,今天学习了如何用通用定时器实现1s延时,使LED灯闪烁,现总结如下:
步骤总结:
使能定时器时钟->配置定时器结构体->清空定时器标志位->开启定时器中断->使能定时器->编写中断服务函数
Timer.c:
- #include "Timer.h"
- void TimerBase_Config(void)
- {
- //开时钟
- RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
- //定义结构体变量
- TIM_TimeBaseInitTypeDef TimerBaseInitStructure;
- NVIC_InitTypeDef NVICInitStructure;
- //配置定时器结构体
- TimerBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1;
- TimerBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up;
- TimerBaseInitStructure.TIM_Period = 10000;
- TimerBaseInitStructure.TIM_Prescaler = 7200;
- TIM_TimeBaseInit(TIM2, &TimerBaseInitStructure);
- //清空标志位
- TIM_ClearFlag(TIM2,TIM_FLAG_Update);
- //开启定时器中断
- TIM_ITConfig(TIM2,TIM_IT_Update,ENABLE);
- //使能定时器
- TIM_Cmd(TIM2,ENABLE);
- //配置NVIC结构体
- NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
- NVICInitStructure.NVIC_IRQChannel = TIM2_IRQn;
- NVICInitStructure.NVIC_IRQChannelCmd = ENABLE;
- NVICInitStructure.NVIC_IRQChannelPreemptionPriority = 1;
- NVICInitStructure.NVIC_IRQChannelSubPriority = 1;
- NVIC_Init(&NVICInitStructure);
- }
复制代码
stm32f103x_it.c:
- void TIM2_IRQHandler(void)
- {
- static uint16_t temp;
- if(TIM_GetITStatus(TIM2,TIM_IT_Update) != RESET)
- {
- if(temp ++ %2 == 1)
- {
- GPIO_ResetBits(LED_G_GPIO_PORT,LED_G_GPIO_PIN);
- }
- else
- {
- GPIO_SetBits(LED_G_GPIO_PORT,LED_G_GPIO_PIN);
- }
- }
- TIM_ClearITPendingBit(TIM2,TIM_IT_Update);
- }
复制代码
main.c:
- #include "stm32f10x.h"
- #include "led.h"
- #include "Timer.h"
- int main(void)
- {
- TimerBase_Config();
- LED_GPIO_Confing();
- GPIO_SetBits(LED_G_GPIO_PORT,LED_G_GPIO_PIN);
- while(1)
- {
- }
- }
复制代码
注意事项:
一定要记得清空标志位,尤其是中断服务函数里的清空标志位,博主就因为此检查好长时间
|