cancel
Showing results for 
Search instead for 
Did you mean: 

STM32F103 TIM Encoder mode not working

ferhatyol-23
Senior

Hello

I am trying to read the Quadrature optical encoder using TIM2 with STM32F103. I've done the Timer settings. But the TIM2->CNT Always zero. I measured the Timer channels with the oscilloscope. The encoder signals reach TIM_CH1 and TIM_CH2.(PA0, PA1)

This is my init code

void ENCODER_TIM_Init(void){
  TIM_Encoder_InitTypeDef TIM_Encoder_Init;
  GPIO_InitTypeDef GPIO_InitStruct;
	
	__HAL_RCC_TIM2_CLK_ENABLE();
	__HAL_RCC_GPIOA_CLK_ENABLE();
	
	/**TIM2 GPIO Configuration    
	PA0-WKUP     ------> TIM2_CH1
	PA1     ------> TIM2_CH2 
	*/
	GPIO_InitStruct.Pin = GPIO_PIN_0|GPIO_PIN_1;
	GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
	GPIO_InitStruct.Pull = GPIO_NOPULL;
	HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
 
  TIM_Handle.Instance = TIM2;
  TIM_Handle.Init.Prescaler = 0;
  TIM_Handle.Init.CounterMode = TIM_COUNTERMODE_UP;
  TIM_Handle.Init.Period = 0;
  TIM_Handle.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
 
  TIM_Encoder_Init.EncoderMode = TIM_ENCODERMODE_TI12;
  TIM_Encoder_Init.IC1Polarity = TIM_ICPOLARITY_RISING;
  TIM_Encoder_Init.IC1Selection = TIM_ICSELECTION_DIRECTTI;
  TIM_Encoder_Init.IC1Prescaler = TIM_ICPSC_DIV1;
  TIM_Encoder_Init.IC1Filter = 0x00;
  TIM_Encoder_Init.IC2Polarity = TIM_ICPOLARITY_RISING;
  TIM_Encoder_Init.IC2Selection = TIM_ICSELECTION_DIRECTTI;
  TIM_Encoder_Init.IC2Prescaler = TIM_ICPSC_DIV1;
  TIM_Encoder_Init.IC2Filter = 0x00;
	
  if (HAL_TIM_Encoder_Init(&TIM_Handle, &TIM_Encoder_Init) != HAL_OK)
  {
    _Error_Handler(__FILE__, __LINE__);
  }
	
	if(HAL_TIM_Encoder_Start(&TIM_Handle, TIM_CHANNEL_ALL) != HAL_OK)
	{
		Error_Handler();
	}
}

What could be the problem?

1 ACCEPTED SOLUTION

Accepted Solutions
ferhatyol-23
Senior

I solved the problems. I made a mistake timer settings. The TIM period should not be zero.

View solution in original post

1 REPLY 1
ferhatyol-23
Senior

I solved the problems. I made a mistake timer settings. The TIM period should not be zero.