AnsweredAssumed Answered

Use User button of STM32F4 as encoder mode (Timer)

Question asked by bouzouita.badred.001 on Dec 21, 2013
Latest reply on Dec 22, 2013 by Clive One
Hey

In order to use the user button of stm32f4 discovery as encoder mode, I was configured timer2 as follows but it didn't work: 
void configureEncoder(void) {
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE);// Enable GPIO_B
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);// ENABLE TIM2
// Configure PA.00 as Alternative Function in order to it connect to TI2 (external clock)
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF; // Input/Output controlled by peripheral
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_0;// Use the button as external source clock
GPIO_Init(GPIOA, &GPIO_InitStructure);
// Connect the pins to their Alternate Functions
GPIO_PinAFConfig(GPIOA, GPIO_PinSource0, GPIO_AF_TIM2);
 
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_TimeBaseStructure.TIM_Period = 0xffff;// max resolution
TIM_TimeBaseStructure.TIM_Prescaler = 0;
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);
 
/* Configure the timer */
TIM_EncoderInterfaceConfig(TIM2, TIM_EncoderMode_TI2, TIM_ICPolarity_Rising, TIM_ICPolarity_Rising);
TIM_SetAutoreload (TIM2, 0xffff);
 
/* Enable the TIM2 gloabal Interrupt */
NVIC_InitTypeDef   NVIC_InitStructure ;
    NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQn;
    NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
    NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;
    NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
    NVIC_Init(&NVIC_InitStructure);
 
/* TIM IT enable */
    TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE);
    /* TIM2 enable counter */
 
TIM_ICInitTypeDef TIM_ICInitStructure;
 TIM_ICInitStructure.TIM_Channel     = TIM_Channel_2;
 TIM_ICInitStructure.TIM_ICPolarity  = TIM_ICPolarity_Rising;
 TIM_ICInitStructure.TIM_ICSelection = TIM_ICSelection_DirectTI;
 TIM_ICInitStructure.TIM_ICPrescaler = TIM_ICPSC_DIV1;
 TIM_ICInitStructure.TIM_ICFilter    = 0x0;
 TIM_ICInit(TIM2, &TIM_ICInitStructure);
    /* TIM2 counter enable */
    TIM_Cmd(TIM2, ENABLE);
}
// IRQ function
void TIM2_IRQHandler(void) // PASS takes approx 500ns of CPU time!
{
    if (TIM_GetITStatus(TIM2, TIM_IT_Update) != RESET)
    {
        //TODO: Interrupt Implement Me!!
        //TIM_GetCounter(TIM9)
     counter=TIM2->CNT;// _GetCounter(TIM2);
GPIO_SetBits(GPIOD,GPIO_Pin_13);
GPIO_ResetBits(GPIOD,GPIO_Pin_12);
 
    }
 
    // Clear the interrupt
    TIM_ClearITPendingBit(TIM2, TIM_IT_Update);
}

Outcomes