cancel
Showing results for 
Search instead for 
Did you mean: 

can't use TIM21 as pulse counter STM32L051

Johanan1
Associate II

I try to count pulses from PA1 as TIM21_ETR, seems like all setting is OK, but no counting what soever. What am I missing?

Thanks

/* TIM21 init function */
void MX_TIM21_Init(void)
{
  TIM_ClockConfigTypeDef sClockSourceConfig;
  TIM_MasterConfigTypeDef sMasterConfig;
 
  htim21.Instance = TIM21;
  htim21.Init.Prescaler = 0;
  htim21.Init.CounterMode = TIM_COUNTERMODE_UP;
  htim21.Init.Period = 0;
  htim21.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
  if (HAL_TIM_Base_Init(&htim21) != HAL_OK)
  {
    Error_Handler();
  }
 
  sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_ETRMODE2;
  sClockSourceConfig.ClockPolarity = TIM_CLOCKPOLARITY_NONINVERTED;
  sClockSourceConfig.ClockPrescaler = TIM_CLOCKPRESCALER_DIV1;
  sClockSourceConfig.ClockFilter = 0;
  if (HAL_TIM_ConfigClockSource(&htim21, &sClockSourceConfig) != HAL_OK)
  {
    Error_Handler();
  }
 
  sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
  sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
  if (HAL_TIMEx_MasterConfigSynchronization(&htim21, &sMasterConfig) != HAL_OK)
  {
    Error_Handler();
  }
  HAL_TIM_Base_MspInit(&htim21);
}
 
 
void HAL_TIM_Base_MspInit(TIM_HandleTypeDef* tim_baseHandle)
{
 
  GPIO_InitTypeDef GPIO_InitStruct;
  if(tim_baseHandle->Instance==TIM21)
  {
  /* USER CODE BEGIN TIM21_MspInit 0 */
 
  /* USER CODE END TIM21_MspInit 0 */
    /* TIM21 clock enable */
    __HAL_RCC_TIM21_CLK_ENABLE();
  
    /**TIM21 GPIO Configuration    
    PA1     ------> TIM21_ETR 
    */
    GPIO_InitStruct.Pin = GPIO_PIN_1;
    GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
    GPIO_InitStruct.Pull = GPIO_NOPULL;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
    GPIO_InitStruct.Alternate = GPIO_AF5_TIM21;
    HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
 
  /* USER CODE BEGIN TIM21_MspInit 1 */
 
  /* USER CODE END TIM21_MspInit 1 */
  }
}

5 REPLIES 5

Read out and check/post content of relevant GPIO and TIM registers.

JW

Johanan1
Associate II

Thanks, that is strange ( I think).

All TIM21 registers are 0x0000 except

SMCR = 0x00004000 and

SR = 0x00000001

Johanan1
Associate II

GPIOA:

0690X000006C5k1QAC.png

Johanan1
Associate II

found it, need ARR = 0xFFFF and timer need to be anabled , CR1 = 0x01

If resolved, mark as so (Best). Thanks.

JW