cancel
Showing results for 
Search instead for 
Did you mean: 

Missing counter using TIMER input count

Alan Tan
Associate II

Hi all,

I'm using nucleo STM32 L4R5ZI .

Using systick 120Mhz as clock

and set timer 2 , channel 1 as TIM_TS_TI1FP1 (Trigger and rising edge)

Then, using

int count = __HAL_TIM_GetCounter(&htim2); to sample the count for every 1ms.

Input 40KHz .

By right, the count for every 1ms is 40.

Somehow, a count will miss on every 4th ms, will be 39 for 4th, 8th 12thms.

Anyone has any idea what is going wrong?

  /* USER CODE BEGIN TIM2_Init 0 */
 
  /* USER CODE END TIM2_Init 0 */
 
  TIM_SlaveConfigTypeDef sSlaveConfig = {0};
  TIM_MasterConfigTypeDef sMasterConfig = {0};
 
  /* USER CODE BEGIN TIM2_Init 1 */
 
  /* USER CODE END TIM2_Init 1 */
  htim2.Instance = TIM2;
  htim2.Init.Prescaler = 0;
  htim2.Init.CounterMode = TIM_COUNTERMODE_UP;
  htim2.Init.Period = TIMER_MAX;
  htim2.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
  htim2.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
  if (HAL_TIM_Base_Init(&htim2) != HAL_OK)
  {
    Error_Handler();
  }
  sSlaveConfig.SlaveMode = TIM_SLAVEMODE_EXTERNAL1;
  sSlaveConfig.InputTrigger = TIM_TS_TI1FP1;
  sSlaveConfig.TriggerPolarity = TIM_TRIGGERPOLARITY_RISING;
  sSlaveConfig.TriggerFilter = 15;
  if (HAL_TIM_SlaveConfigSynchro(&htim2, &sSlaveConfig) != HAL_OK)
  {
    Error_Handler();
  }
  sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
  sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
  if (HAL_TIMEx_MasterConfigSynchronization(&htim2, &sMasterConfig) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN TIM2_Init 2 */
 
  /* USER CODE END TIM2_Init 2 */
	int count =  __HAL_TIM_GetCounter(&htim2);

4 REPLIES 4

One or both clocks (i.e. the external signal and the STM32 clock) may be unprecise. The difference is roughly 1 in 160, i.e. around 0.6%.

What is the primary clock source in STM32, MSI or HSI or HSE?

What is the 40kHz signal's source?

JW

PS. Please change your user name to a normal nick.

How good is your external clock source (HSE) or are you relying of VCO/PLL and HSI of some pretty arbitrary accuracy?

Perhaps quantify 120 MHz in TIM2 or TIM5 vs a GPS 1PPS input.

Tips, Buy me a coffee, or three.. PayPal Venmo
Up vote any posts that you find helpful, it shows what's working..

40k signal source is coming from function generator for testing.

I set to 120Mhz using PLL.

That is probably PLL clock is not accurate.

I should try from crystal oscillator

I'm relying on PLL.

Tim2 40Khz was coming from function generator.