2023-01-22 11:16 AM
Hi All,
First post :beaming_face_with_smiling_eyes:
I want to count external pulses with a STM32F105 or STM32F405 using the HAL library.
I want the external pulses to increment the timer counter.
I want to avoid using interrupts. Instead, I want to read and clear the timer counter within a round-robin.
Cheers
2023-01-22 12:16 PM
The code below uses Timer2 and PA0 as a clock source. Unfortunately, it doesn't work :\
GPIO_InitTypeDef GPIO_InitStruct;
TIM_HandleTypeDef htim2;
uint32_t button_timer = 0;
bool button_timer_configured = false;
uint32_t capture;
void GPIO_Init(void)
{
__HAL_RCC_GPIOA_CLK_ENABLE();
GPIO_InitStruct.Pin = GPIO_PIN_0;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
GPIO_InitStruct.Alternate = GPIO_AF1_TIM2;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
}
void TIM2_IC_Init(void)
{
htim2.Instance = TIM2;
htim2.Init.Prescaler = 0;
htim2.Init.CounterMode = TIM_COUNTERMODE_UP;
htim2.Init.Period = 0xFFFFFFFF;
htim2.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
HAL_TIM_IC_Init(&htim2);
TIM_IC_InitTypeDef sConfigIC;
sConfigIC.ICPolarity = TIM_ICPOLARITY_RISING;
sConfigIC.ICSelection = TIM_ICSELECTION_DIRECTTI;
sConfigIC.ICPrescaler = TIM_ICPSC_DIV1;
sConfigIC.ICFilter = 0;
HAL_TIM_IC_ConfigChannel(&htim2, &sConfigIC, TIM_CHANNEL_1);
HAL_TIM_IC_Start(&htim2, TIM_CHANNEL_1);
}
void Application(void)
{
if (!button_timer_configured)
{
GPIO_Init();
TIM2_IC_Init(); // Initialize Timer 2 in input capture mode
button_timer = mstimer_get_ms_tick();
button_timer_configured = true;
}
if (mstimer_timeout(&button_timer, 10000))
{
capture = __HAL_TIM_GET_COMPARE(&htim2, TIM_CHANNEL_1); // Read captured value
}
}
2023-01-22 12:34 PM
Why not using the pulse as free run and overflow timer clock source, so that every 1 second, substract timer snapshot with 1 second before, to get result in Hz?
2023-01-22 01:30 PM
Input Capture (IC) captures (copies) the timer counter to a timer channel register, this is not what you want for counting pulses. You want to use ETR (external trigger) mode creating counter pulses from an external pin and read out the timer counter register.
Have seen projects on the web, your search engine will find them.
hth
KnarfB
2023-01-22 02:16 PM
Thanks KnarfB,
Found a post detailing how to use ETR to count pulses. It worked a treat :beaming_face_with_smiling_eyes: :
I know it's a little wasteful, but I have plenty of timers ;)