欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

定时器中断实验

程序员文章站 2022-06-09 08:54:32
...

定时器中断实验定时器中断实验

常用库函数:定时器参数初始化

void TIM_TimeBaseInit(TIM_TypeDef* TIMx,

                                            TIM_TimeBaseInitTypeDef* TIM_TimeBaseInitStruct);

typedefstruct

{

  uint16_t TIM_Prescaler;       //预分频系数

  uint16_t TIM_CounterMode;    //计数模式是向上还是向下

  uint16_t TIM_Period;       //自动装载值

  uint16_t TIM_ClockDivision; //捕获里用到

  uint8_t TIM_RepetitionCounter;//高级定时器用到

} TIM_TimeBaseInitTypeDef

--定时器使能函数:

void TIM_Cmd(TIM_TypeDef*TIMx, FunctionalState NewState)

--定时器中断使能函数:

void TIM_ITConfig(TIM_TypeDef*TIMx, uint16_t TIM_IT, FunctionalState NewState);

--状态标志位获取和清除

FlagStatus TIM_GetFlagStatus(TIM_TypeDef*TIMx, uint16_t TIM_FLAG);

void TIM_ClearFlag(TIM_TypeDef*TIMx, uint16_t TIM_FLAG);

ITStatus TIM_GetITStatus(TIM_TypeDef*TIMx, uint16_t TIM_IT);

void TIM_ClearITPendingBit(TIM_TypeDef*TIMx, uint16_t TIM_IT);


--定时器中断实现步骤:
能定时器时钟。

       RCC_APB1PeriphClockCmd();

 初始化定时器,配置ARR,PSC

      TIM_TimeBaseInit();

开启定时器中断,配置NVIC

      void TIM_ITConfig();

      NVIC_Init();

 使能定时器。

      TIM_Cmd();

 编写中断服务函数。

      TIMx_IRQHandler();

Tout(溢出时间)=ARR+1)(PSC+1)/Tclk

通过定时器中断配置,每500ms中断一次,然后中断服务函数中控制LED实现LED1状态取反(闪烁)。

void TIM3_Int_Init(u16 arr ,u16 psc)
{
	TIM_TimeBaseInitTypeDef  TIM_TimeBaseStructure;
	NVIC_InitTypeDef NVIC_InitStructure; 

	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3 , ENABLE);
																		
    TIM_TimeBaseStructure.TIM_Prescaler = arr;			
	TIM_TimeBaseStructure.TIM_Period = psc;		 					
    TIM_TimeBaseStructure.TIM_CounterMode=TIM_CounterMode_Up; 		
    TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);

	TIM_ITConfig(TIM3,TIM_IT_Update,ENABLE);//使能更新中断

	 						  			
    NVIC_InitStructure.NVIC_IRQChannel = TIM3_IRQn;	  			
    NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;	
    NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3;		
    NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;		
    NVIC_Init(&NVIC_InitStructure);											

	TIM_Cmd(TIM3, ENABLE);

    TIM_ClearFlag(TIM2, TIM_FLAG_Update);							    	
    TIM_ITConfig(TIM2,TIM_IT_Update,ENABLE);							
   	
}
void TIM3_IRQHandler(void)
{
	if(TIM_GetITStatus(TIM3 , TIM_IT_Update) != RESET )
	{
		LED1=!LED1;
		TIM_ClearITPendingBit(TIM3 , TIM_FLAG_Update);
	}

}
int main(void)
{
	 NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
	 delay_init();
	 LED_Init();
	 TIM3_Int_Init(4999 ,7199);
	 while(1);
}