通用定时器的工作过程:
内部时钟选择:
默认调用Systemlnit函数情况下:
SYSCLK=168M
AHB时钟=168M
APB1时钟=42M
所以APB1的分频系数=AHBIAPB1时钟=4
所以,通用定时器时钟CK INT=2*42M=84M
计算溢出时间:
Tout=(ARR+1)(PSC+1)/Tclk
500ms中断一次,arr=4999,psc=8399.
在跑马灯程序基础上实现定时器中断步骤:
1、使能定时器时钟:
RCC APB1PeriphClockCmd();
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3,ENABLE);
2、初始化定时器,配置ARR, PSC:
TIM_TimeBaselnit();
TIM_TimeBaseInitStructure.TIM_Period = arr; //自动重装载值
TIM_TimeBaseInitStructure.TIM_Prescaler=psc; //定时器分频
TIM_TimeBaseInitStructure.TIM_CounterMode=TIM_CounterMode_Up; //向上计数模式
TIM_TimeBaseInitStructure.TIM_ClockDivision=TIM_CKD_DIV1;
TIM_TimeBaseInit(TIM3,&TIM_TimeBaseInitStructure);
3、定时器中断使能:
TIM_ITConfig();
TIM_ITConfig(TIM3,TIM_IT_Update,ENABLE);
4、定时器使能:
TIM_Cmd();
TIM_Cmd(TIM3,ENABLE);
5、开启定时器中断,配置NVIC:
NVIC_Init();
NVIC_InitStructure.NVIC_IRQChannel=TIM3_IRQn; //定时器3中断
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=0x01; //抢占优先级
NVIC_InitStructure.NVIC_IRQChannelSubPriority=0x03; //响应优先级
NVIC_InitStructure.NVIC_IRQChannelCmd=ENABLE;
NVIC_Init(&NVIC_InitStructure);
6、编写中断服务函数:
TIM3_IRQHandler();
void TIM3_IRQHandler(void)
{
if(TIM_GetITStatus(TIM3,TIM_IT_Update)==SET)
{
LED1=!LED1;
}
TIM_ClearITPendingBit(TIM3,TIM_IT_Update);
7、编写main.c:
int main(void)
{
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
delay_init(168);
LED_Init();
TIM3_Int_Init(5000-1,8400-1);
while(1)
{
LED0=!LED0;
delay_ms(200);
};
}