Configuring LPTIM to generate autoreload interrupts on STM32L4
Hi,
I am trying to learn how to use the LPTIM1 of the STM32L433 Nucleo-64 board (with the CPU: STM32L433RCTxP). I want to experiment on generating an interrupt every second with the LPTIM (I usually use a TIMx peripheral for this, but was interested because the LPTIM1 could also run in STOP modes).
I sort of have a working code where the LPTIM1 generates an interrupt periodically, although not at every second (or at a rate of 1Hz):
/* Note: SYSCLK, HCLK, PCLK1, PCLK2 are all 16MHz running on HSI */
static void MX_LPTIM1_Init(void)
{
hlptim1.Instance = LPTIM1;
hlptim1.Init.Clock.Source = LPTIM_CLOCKSOURCE_APBCLOCK_LPOSC;
hlptim1.Init.Clock.Prescaler = LPTIM_PRESCALER_DIV128;
hlptim1.Init.Trigger.Source = LPTIM_TRIGSOURCE_SOFTWARE;
hlptim1.Init.OutputPolarity = LPTIM_OUTPUTPOLARITY_HIGH;
hlptim1.Init.UpdateMode = LPTIM_UPDATE_IMMEDIATE;
hlptim1.Init.CounterSource = LPTIM_COUNTERSOURCE_INTERNAL;
hlptim1.Init.Input1Source = LPTIM_INPUT1SOURCE_GPIO;
hlptim1.Init.Input2Source = LPTIM_INPUT2SOURCE_GPIO;
if (HAL_LPTIM_Init(&hlptim1) != HAL_OK)
{
Error_Handler();
}
HAL_NVIC_SetPriority(LPTIM1_IRQn, 1, 0);
HAL_NVIC_EnableIRQ(LPTIM1_IRQn);
/* 65535 is the value loaded into LPTIM1's ARR register */
HAL_LPTIM_Counter_Start_IT(&hlptim1, 65535);
}
/*** Code portion below in the interrupt C file ***/
static uint32_t counter = 0;
/**
* @brief Autoreload match callback in non blocking mode
* @param hlptim : LPTIM handle
* @retval None
*/
void HAL_LPTIM_AutoReloadMatchCallback(LPTIM_HandleTypeDef *hlptim)
{
/* Blink onboard LED */
if(counter >= 2)
{
/* TODO: Do some task here */
Func1();
counter = 0;
}
counter++;
}With the inclusion of the if(counter>=2) block, Func1() executes periodically at a slightly higher rate than 1Hz. I measured the time duration between each function call with my phone's stopwatch and I would say that the duration between each function call is around 0.9 seconds. (The way I tested it was to blink the LED at interrupt execution and measure the blinking LEDs with a stopwatch. This procedure was pretty accurate when I was testing a 1 second interrupt execution with TIM2).
I am wondering what the equation for the interrupt execution frequency rates (Hz) looks like for the LPTIM peripherals, and how to set up the LPTIM peripherals to produce an interrupt periodically properly. Is there an example parameter where I could generate an interrupt every second?
I also noticed that from this datasheet, TIM6 does not use that much more current than LPTIM1 does in Low Power Run mode. Aside from the LPTIMs being able to run in STOP mode and not requiring HSI as the clock source, what is the difference between TIM and LPTIM? If my application only requires the STM32 microcontroller to operate in low power run mode, would using the TIM6 to generate periodical interrupts be better than using LPTIM1?
Any advice/help would be greatly appreciated. Thank you!