cancel
Showing results for 
Search instead for 
Did you mean: 

The timer input mode is not working. (using STM32F103RB)

dKim.1
Associate II

Hi all,

I test the timer input capture mode.

The input range is 1Hz ~ 100Hz.

I set the parameter as below. (Using CUBEMX)

  1. Timer Clock : 60Mhz
  2. PSC : 6000
  3. ARR: 10000
void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef *htim)
{
  HAL_GPIO_WritePin(LED_PORT, IN_LED_PIN, GPIO_PIN_SET);
 
  if (Is_First_Captured == 0)
  {
    IC_Value1 = HAL_TIM_ReadCapturedValue(&htim2, TIM_CHANNEL_2);          
    Is_First_Captured = 1;
  }
  else if (Is_First_Captured)
  {
    IC_Value2 = HAL_TIM_ReadCapturedValue(&htim2, TIM_CHANNEL_2);   
    __HAL_TIM_SET_COUNTER(&htim2, 0);
 
    if (IC_Value2 > IC_Value1)
    {
      Period = IC_Value2 - IC_Value1;
    }
    else if (IC_Value2 < IC_Value1)
    {
      Period = ((htim2.Instance->ARR - IC_Value1) + IC_Value2) + 1;
    }
    else
    {
      Error_Handler();
    }    
    Frequency = (2*HAL_RCC_GetPCLK1Freq())/(htim2.Instance->PSC + 1);
    Frequency = Frequency / Period;
    Is_First_Captured = 0;
  }
}

When I measure the frequency, the frequency value is not correct.

Anyone check the my code and parameter, please help me.

I searching for the reason at google but I have not been solve it.

4 REPLIES 4
KnarfB
Principal III

As you compute the difference between two timestamps, you should not set the counter to 0 but leave it counting as is.

Think of a wall clock which you read twice to find the time elapsed, you don't ever set it.

Hi

Thank you for your answer.

As your comment, I deleted the counter set to 0.

But It doesn't work well.

I use the timer2 channel 2.

Should I use the channel 1?

> But It doesn't work well.

This is not a helpful description

Hi,

I'm sorry.

I want to measure the frequency which range 1hz ~ 100.

But I don't understand how presacle and counter peroid are affect to measure.

I using the STM32F103RB and PA1 is used as pulse input pin.(TIMER2 CHANNEL2)

So Could you explain about Prescale and Counter period for measure the frequency?

Below is my CubeMx screen shot.

0693W000007DMd4QAG.png 

0693W000007DMcBQAW.png

And code is

  if (htim->Channel == HAL_TIM_ACTIVE_CHANNEL_2)
  {
    if (Is_First_Captured == 0)
    {
      IC_Value1 = HAL_TIM_ReadCapturedValue(htim, TIM_CHANNEL_2);    
      Is_First_Captured = 1;
    }
    else if (Is_First_Captured)
    {
      IC_Value2 = HAL_TIM_ReadCapturedValue(htim, TIM_CHANNEL_2);
 
      if (IC_Value2 > IC_Value1)
      {
        Period = IC_Value2 - IC_Value1;
      }
      else if (IC_Value2 < IC_Value1)
      {
        Period = ((htim2.Instance->ARR - IC_Value1) + IC_Value2) + 1;
      }
      else
      {
        Error_Handler();
      }    
 
      Frequency = (2*HAL_RCC_GetPCLK1Freq()) / Period;     
      Is_First_Captured = 0;
    }
  }