cancel
Showing results for 
Search instead for 
Did you mean: 

Count External Pulses Using Timer

Lee Davies
Associate II

Hi All,

First post 😁

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

4 REPLIES 4
Lee Davies
Associate II

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
    }
}

S.Ma
Principal

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?

KnarfB
Principal III

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

Thanks KnarfB,

Found a post detailing how to use ETR to count pulses. It worked a treat 😁 :

I know it's a little wasteful, but I have plenty of timers 😉

0693W00000Y8r9DQAR.png