那么我们直接看代码: 定时器初始化设置 void TIM3_Int_Init()
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;
TIM_ICInitTypeDef TIM_ICInitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3,ENABLE);
//定时器设置-------------------------------------------------------------
TIM_TimeBaseInitStructure.TIM_Period = 359*4; //重装载值
TIM_TimeBaseInitStructure.TIM_Prescaler=0x0; //预分频
TIM_TimeBaseInitStructure.TIM_CounterMode=TIM_CounterMode_Up; //向上计数
TIM_TimeBaseInitStructure.TIM_ClockDivision=TIM_CKD_DIV1; //时钟分割
TIM_TimeBaseInit(TIM3,&TIM_TimeBaseInitStructure);//初始化TIM3
//编码器模式设置--------------------------------------------------------------
TIM_EncoderInterfaceConfig(TIM3,TIM_EncoderMode_TI12,TIM_ICPolarity_Rising, TIM_ICPolarity_Rising);//计数模式3
TIM_ICStructInit(&TIM_ICInitStructure); //将结构体中的内容缺省输入
TIM_ICInitStructure.TIM_ICFilter = 0;//滤波器值
TIM_ICInit(TIM3, &TIM_ICInitStructure); //将TIM_ICInitStructure中的指定参数初始化TIM3
//溢出中断设置--------------------------------------------------------------
TIM_ITConfig(TIM3,TIM_IT_Update,ENABLE); //允许TIM3溢出中断
NVIC_InitStructure.NVIC_IRQChannel=TIM3_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=0x01;
NVIC_InitStructure.NVIC_IRQChannelSubPriority=0x01;
NVIC_InitStructure.NVIC_IRQChannelCmd=ENABLE;
NVIC_Init(&NVIC_InitStructure);
TIM_SetCounter(TIM3,0); //TIM3->CNT=0
TIM_Cmd(TIM3, ENABLE);
}
重装载值: (编码器线数-1 ) *4 因为我们是两相计数,一个脉冲信号4次计数,所以乘4,保证转完1整圈才触发中断 中断设置: int circle_count=0;//圈数
void TIM3_IRQHandler(void)
{
if(TIM_GetITStatus(TIM3,TIM_IT_Update)==SET)
{
if((TIM3->CR1>>4 & 0x01)==0) //DIR==0
circle_count++;
else if((TIM3->CR1>>4 & 0x01)==1)//DIR==1
circle_count--;
}
TIM_ClearITPendingBit(TIM3,TIM_IT_Update);
}
|