l 使能定时器时钟。
RCC_APB1PeriphClockCmd();
l 初始化定时器,配置ARR,PSC。
TIM_TimeBaseInit();
l 开启定时器中断,配置NVIC。
void TIM_ITConfig();
NVIC_Init();
l 使能定时器。
TIM_Cmd();
l 编写中断服务函数。
TIMx_IRQHandler();
l 源代码:
//Tout(溢出时间)=(ARR+1)(PSC+1)/Tclk
//500ms -> (4999+1)( 7199+1)/72000000 = 0.5s = 500ms
void TIM3_Int_Init(u16 arr,u16 psc)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
NVIC_InitTypeDef NVIC_InitStructure; RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE); //时钟使能 //定时器TIM3初始化
TIM_TimeBaseStructure.TIM_Period = arr; //设置更新装载值
TIM_TimeBaseStructure.TIM_Prescaler =psc;//设置预分频值
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1; //设置时钟分割
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; //TIM向上计数模式
TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure); TIM_ITConfig(TIM3,TIM_IT_Update,ENABLE ); //允许更新中断 //中断优先级NVIC设置
NVIC_InitStructure.NVIC_IRQChannel = TIM3_IRQn; //TIM3中断
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = ; //0抢占优先级
NVIC_InitStructure.NVIC_IRQChannelSubPriority = ; //响应优先级
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //IRQ通道势能
NVIC_Init(&NVIC_InitStructure); //初始化NVIC寄存器 TIM_Cmd(TIM3, ENABLE); //使能TIM
}
//定时器3中断服务程序
void TIM3_IRQHandler(void)
{
if (TIM_GetITStatus(TIM3, TIM_IT_Update) != RESET) //检查是否更新中断
{
TIM_ClearITPendingBit(TIM3, TIM_IT_Update ); //清楚更新中断
LED1=!LED1;
}
}
int main(void)
{
delay_init();
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);//抢占和响应优先级的范围0~3
uart_init();
LED_Init();
TIM3_Int_Init(,);
while()
{
LED0=!LED0;
delay_ms();
}
}