cancel
Showing results for 
Search instead for 
Did you mean: 

Quadrature encoder - differentiating rotation direction

stefanskos9
Associate II
Posted on September 12, 2013 at 23:38

Hi,

I have a quadratutre encoder set up, and it seems to work fine in one direction with the CNT of the timer incrementing correctly. However when the shaft spins the other way, CNT remains zero. How can I increment/decrement CNT when the shaft spins anticlockwise? If CNT decrements, would I have to minus CNT from 65535? How Do I know the direction its spinning? Below is my code;

//PA0 TIM5_ch1 = enc a
//PA1 TIM5_ch2 = enc b
// Enable GPIO clock
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA,ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM5,ENABLE);
// PA0 & PA1 for encoder 
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_Init(GPIOA,&GPIO_InitStructure);
GPIO_PinAFConfig(GPIOA, GPIO_PinSource0, GPIO_AF_TIM5);
GPIO_PinAFConfig(GPIOA, GPIO_PinSource1, GPIO_AF_TIM5);
//Configure Timer
TIM_TimeBaseStructInit(&TIM_TimeBaseStructure); 
TIM_TimeBaseStructure.TIM_Prescaler = 0;
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseStructure.TIM_Period = 65535;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; 
TIM_TimeBaseInit(TIM5, &TIM_TimeBaseStructure);
//Setup quadrature encoder and enable timer
TIM_EncoderInterfaceConfig(TIM5,TIM_EncoderMode_TI12,TIM_ICPolarity_Rising,TIM_ICPolarity_Rising);
TIM_Cmd(TIM5, ENABLE); 
TIM5->CNT = 0;

Thanks for your help in advance! #timer-encoder-qei
1 REPLY 1
jpeacock2399
Associate II
Posted on September 13, 2013 at 00:54

Check the two phases from the encoder.  They should be square waves 90 degrees apart while the shaft is turning.  If both phases align on the same edge you have a hardware problem.  If the phases are correct you should see increment or decrement according to turn direction.  The timer will roll over from 0 to 0xffff and continue counting down.  Since oyu only see one direction there appears to be something wrong with your inputs.  Is the encoder single ended or differential?

You might want to set your period to the encoder wheel count.  That way your timer count is proportional to the angle of the shaft.

  Jack Peacock