一个完整的代码例子
下面我们将完成一个定时器1毫秒溢出中断的程序,注意我这个的前提的APB1 = AHB/4, AHB = 200M,具体配置请看上面的描述;
//定时器初始化
void time1_init(void)
{
timer_parameter_struct timer_initpara;//定时器结构体
rcu_periph_clock_enable(RCU_TIMER1);//开启定时器时钟
//因为APB1是AHB的4分频,因此定时器时钟CK_TIMERx = CK_AHB = 200m
rcu_timer_clock_prescaler_config(RCU_TIMER_PSC_MUL4);//配置定时器时钟等于CK_AHB
timer_struct_para_init(&timer_initpara);//将定时器结构体内参数配置成默认参数
timer_deinit(TIMER1); //复位定时器
/* TIMER1 configuration */
//200M/200/1000 = 1k
timer_initpara.prescaler = 200-1;//预分频
timer_initpara.alignedmode = TIMER_COUNTER_EDGE; //边缘对齐
timer_initpara.counterdirection = TIMER_COUNTER_UP; //向上计数方式
timer_initpara.period = 1000-1; //计数值
timer_initpara.clockdivision = TIMER_CKDIV_DIV1;
timer_initpara.repetitioncounter = 0; //每次溢出都产生更新是件
timer_init(TIMER1,&timer_initpara);
/* auto-reload preload enable */
timer_auto_reload_shadow_enable(TIMER1);//使能自动重加载
timer_interrupt_enable(TIMER1,TIMER_INT_UP);//使能溢出中断
nvic_irq_enable(TIMER1_IRQn, 0, 1);//配置中断优先级
/* TIMER1 enable */
timer_enable(TIMER1);//使能定时器
}
//main函数
int main(void)
{
nvic_priority_group_set(NVIC_PRIGROUP_PRE2_SUB2);//配置优先级分组
timer1_init();
}
//中断函数
void TIMER1_IRQHandler(void)
{
if(SET == timer_interrupt_flag_get(TIMER1,TIMER_INT_UP)){
//用户代码
/* clear TIMER interrupt flag */
timer_interrupt_flag_clear(TIMER1,TIMER_INT_UP);
}
}
|