/***************************************初始化*********************************/
void Encoder_TIM5_INIT(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_ICInitTypeDef TIM_ICInitStructure;
// NVIC_InitTypeDef NVIC_InitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM5,ENABLE);//开启TIM5时钟
RCC_AHB1PeriphClockCmd( RCC_AHB1Periph_GPIOA, ENABLE );
GPIO_PinAFConfig(GPIOA,GPIO_PinSource0,GPIO_AF_TIM5);//开启GPIOA0的TIM5时钟引脚
GPIO_PinAFConfig(GPIOA,GPIO_PinSource1,GPIO_AF_TIM5);//开启GPIOA1的TIM5时钟引脚
GPIO_StructInit(&GPIO_InitStructure);//
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;//PA0 PA1
// GPIO_InitStructure.GPIO_OType = GPIO_OType_OD;//
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;//上拉
GPIO_Init(GPIOA, &GPIO_InitStructure);
/*
NVIC_InitStructure.NVIC_IRQChannel = TIM5_IRQn; //TIME5更新中断
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
*/
//配置编码器模式
TIM_DeInit(TIM5);
TIM_TimeBaseStructInit(&TIM_TimeBaseStructure);
TIM_TimeBaseStructure.TIM_Period = 0xffffffff; ////自动重装载值
TIM_TimeBaseStructure.TIM_Prescaler = 0; //TIM
TIM_TimeBaseStructure.TIM_ClockDivision =TIM_CKD_DIV1 ;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM5, &TIM_TimeBaseStructure);
TIM_EncoderInterfaceConfig(TIM5, TIM_EncoderMode_TI12, TIM_ICPolarity_BothEdge,TIM_ICPolarity_BothEdge);
TIM_ICStructInit(&TIM_ICInitStructure);//
TIM_ICInitStructure.TIM_ICFilter = 6; //
TIM_ICInit(TIM5, &TIM_ICInitStructure);//
TIM_ClearFlag(TIM5, TIM_FLAG_Update);//
TIM_ITConfig(TIM5, TIM_IT_Update, ENABLE);//
//Reset counter
TIM5->CNT = HALF_TIM5_CNTR;//
TIM_Cmd(TIM5, ENABLE); //
}
/***********************************TIME5 中断********************************************************/
void TIM5_IRQHandler(void) //TIM3
{
TIM5->CNT = HALF_TIM5_CNTR;//
TIM_ClearITPendingBit(TIM5, TIM_IT_Update );
}
编码器信号:
我用的MCU是STM32F401CB
我用TIM5 (32位)做编码器接口,程序如上面。编码器是光栅尺输出的正交脉冲(如上图),读出来的数据总是不对。
我尝试作了如下更改,发现如下
1,当我把:TIM_EncoderInterfaceConfig(TIM5, TIM_EncoderMode_TI12, TIM_ICPolarity_BothEdge,TIM_ICPolarity_BothEdge);//
改成:TIM_EncoderInterfaceConfig(TIM5, TIM_EncoderMode_TI1, TIM_ICPolarity_BothEdge,TIM_ICPolarity_BothEdge);//
读出来是的数据是正确数据的一半。
这样应该是只是计了CH1 (PA0)的数,这是正确的。说明CH1的脉冲数应该是读正确了吧?
当我改成:TIM_EncoderInterfaceConfig(TIM5, TIM_EncoderMode_TI2, TIM_ICPolarity_BothEdge,TIM_ICPolarity_BothEdge);//
这样应该是只读CH2 (PA1)的数吧!但读出来的数据总是错误的。
硬件查来查去都没有发现有问题啊!
弄了几天了,都没有解决问题!
求助啊!
万分感激!
|