STM32L4 LPTIM as pulse counter of intermittent pulses fails when initialising with no pulse
I'm working with LPTIM as a Pulse Counter on a STM32L432KC, I have a rain gauge connected to LPTIM1 (PB5) and a anemometer to LPTIM2 (PB1). Both configured on STM32CubeMX as Standalone: counts external clock events and pins assigned as LPTIM?_IN1 using LSE clock.
To simplify, let's just use the anemometer but the symptoms is happening on the rain gauge as well.
Initializing the counter:
HAL_LPTIM_Counter_Start(&hlptim2, 0xffff);This returns HAL_TIMEOUT when there's no pulse (no wind). If I turn the anemometer with my hand or is winding, when the device is initializing, it returns HAL_OK and it works just fine after that.
Troubleshooting, I found where it's timing out. On stm32l4xx_hal_lptim.c,, HAL_LPTIM_Counter_Start function, you can find this code:
/* Load the period value in the autoreload register */
__HAL_LPTIM_AUTORELOAD_SET(hlptim, Period);
/* Wait for the completion of the write operation to the LPTIM_ARR register */
if (LPTIM_WaitForFlag(hlptim, LPTIM_FLAG_ARROK) == HAL_TIMEOUT)
{
return HAL_TIMEOUT;
}There's application note AN4865 related to use LPTIM as a pulse counter and it doesn't say anything about LPTIM_ARR register neither LPTIM_ISR waiting for ARROK flag (4th bit). Also, on the example code, they expect a constant pulse signal arriving so this problem never happens.
If I comment if (LPTIM_WaitForFlag... block, it works perfectly.
I opened the issue on github: https://github.com/STMicroelectronics/STM32CubeL4/issues/24