I'm trying to use TIM4 for quadrature encoder input on my STM32F4DISCOVERY board. Here is my code :
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOB, ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4, ENABLE);
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6| GPIO_Pin_7;
GPIO_Init(GPIOB, &GPIO_InitStructure);
GPIO_PinAFConfig(GPIOB, GPIO_PinSource6, GPIO_AF_TIM4);
GPIO_PinAFConfig(GPIOB, GPIO_PinSource7, GPIO_AF_TIM4);
/* Configure the timer */
TIM_EncoderInterfaceConfig(TIM4, TIM_EncoderMode_TI12, TIM_ICPolarity_Rising, TIM_ICPolarity_Rising);
/* TIM4 counter enable */
TIM_Cmd(TIM4, ENABLE);
sadly, the TIM4->CNT counter won't move when I turn the encoder. I works perfectly with TIM8. Here is the full code of the working TIM8 and the not working TIM4 : https://gist.github.com/nraynaud/5082298
I check by printing rT2() in gdb after moving the encoder by hand.
I have used an STM32F407 to read encoder counts from 3 optical encoders. I am using ChibiOS RTOS so the timer struct is slightly different from the ST Peripheral library timer struct, but the information is basically the same. Here is how I configure the registers of the actual timers:
Also, make sure you enable the timer peripherals in the APB1 or APB2 registers of the RCC. Something like:
Finally, you need to make sure you configure the GPIO settings correctly. This means configuring the GPIO for Alternate Function.
encoder with standard driver
You may need to use pull ups for input unless you are using external resistors or powering the encoder. I usually connect encoder to ground and use internal pull ups to set idle state.