Hardware quadrature encoder in STM32L475

I can’t get the hardware encoder to work on B-L475E-IOT01A1 board. Could someone please tell me what am I doing wrong? TIA

Here is the code :

Blockquote
#include “mbed.h”

DigitalOut led(LED1);

int main()
{
// timer2 as QEI on PA0 & PA1
__TIM2_CLK_ENABLE();
__GPIOA_CLK_ENABLE();

GPIO_InitTypeDef GPIO_InitStruct2;
GPIO_InitStruct2.Pin = GPIO_PIN_0 | GPIO_PIN_1;        
GPIO_InitStruct2.Pull = GPIO_NOPULL;   
GPIO_InitStruct2.Speed = GPIO_SPEED_FREQ_HIGH;
GPIO_InitStruct2.Alternate = GPIO_AF1_TIM2;
HAL_GPIO_Init(GPIOA,&GPIO_InitStruct2);

TIM_HandleTypeDef timer2;
timer2.Instance = TIM2;
timer2.Init.Period = 0xffff;
timer2.Init.Prescaler = 0;
timer2.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
timer2.Init.CounterMode = TIM_COUNTERMODE_UP;

TIM_Encoder_InitTypeDef encoder2;
encoder2.EncoderMode = TIM_ENCODERMODE_TI12;
encoder2.IC1Filter = 0x0f;
encoder2.IC1Polarity = TIM_INPUTCHANNELPOLARITY_RISING;    
encoder2.IC1Prescaler = TIM_ICPSC_DIV1;
encoder2.IC1Selection = TIM_ICSELECTION_DIRECTTI;    
encoder2.IC2Filter = 0x0f;
encoder2.IC2Polarity = TIM_INPUTCHANNELPOLARITY_RISING;    
encoder2.IC2Prescaler = TIM_ICPSC_DIV1;
encoder2.IC2Selection = TIM_ICSELECTION_DIRECTTI;

HAL_TIM_Encoder_Init(&timer2, &encoder2);
HAL_TIM_Encoder_Start(&timer2,TIM_CHANNEL_1);

TIM2->EGR = 1;           // Generate an update event
TIM2->CR1 = 1;           // Enable the counter

while(1)
{
    led = !led;
    printf("T2: %d\n",TIM2->CNT);
    ThisThread::sleep_for(1000);        
}

}