2021-01-30 03:44 AM
Hi all,
I test the timer input capture mode.
The input range is 1Hz ~ 100Hz.
I set the parameter as below. (Using CUBEMX)
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.
2021-01-30 05:17 AM
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.
2021-01-31 05:13 PM
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?
2021-01-31 11:03 PM
> But It doesn't work well.
This is not a helpful description
2021-02-01 12:12 AM
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.
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;
}
}