Skip to content
systemcoding.dev
Embedded

Enter STM32 Stop Mode and Wake on an RTC Alarm

Put an STM32F4 into Stop mode with HAL_PWR_EnterSTOPMode, wake it with an RTC alarm every minute, and restore the clocks that Stop switches off.

6 min read
Summarize in AI
Flat illustration of a microcontroller wired to an LED and a sensor, with the STMicroelectronics, Arm and C logos.

A sensor node that reports once a minute should spend 59.9 seconds of every minute in a low-power mode and a fraction of a second awake. On an STM32F4 the mode for that job is Stop, which keeps SRAM and registers alive, turns off the clocks in the core voltage domain, and lets the real-time clock wake the chip at a set time. The RTC runs from the low-speed oscillator in the backup domain, so it keeps counting through Stop. This post builds a complete program for a NUCLEO-F411RE using STM32CubeF4 HAL 1.28 and arm-none-eabi-gcc 13.3: configure the RTC and an alarm, enter Stop with the HAL, handle the wake-up, and restore the clock tree. Register and bit names come from RM0383, and the HAL names from the STM32F4 HAL driver documentation (UM1725).

The plan

The sequence has five steps, and the order matters:

  1. Run the RTC from the LSE or LSI oscillator and set the time.

  2. Configure alarm A to match on seconds, so it fires once per minute, and enable its interrupt.

  3. Before sleeping, stop the SysTick interrupt so it does not wake the core every millisecond.

  4. Enter Stop with HAL_PWR_EnterSTOPMode.

  5. After the wake-up, reconfigure the system clock, resume SysTick and do the periodic work.

The RTC alarm reaches the core through EXTI line 17. The HAL arranges this when you call HAL_RTC_SetAlarm_IT, which enables the RTC alarm interrupt and the EXTI line that connects it to the wake-up logic. Line 17 is an event source that can wake the chip from Stop.

Configure the RTC and the alarm

This example uses the LSI, the internal 32 kHz RC oscillator, so it needs no external crystal. It is less accurate than a crystal. For a real product, use the LSE.

rtc_init.cc
#include "stm32f4xx_hal.h"

RTC_HandleTypeDef hrtc;

static void rtc_init(void)
{
    RCC_OscInitTypeDef osc = {0};
    osc.OscillatorType = RCC_OSCILLATORTYPE_LSI;
    osc.LSIState = RCC_LSI_ON;
    HAL_RCC_OscConfig(&osc);

    RCC_PeriphCLKInitTypeDef pclk = {0};
    pclk.PeriphClockSelection = RCC_PERIPHCLK_RTC;
    pclk.RTCClockSelection = RCC_RTCCLKSOURCE_LSI;
    HAL_RCCEx_PeriphCLKConfig(&pclk);

    __HAL_RCC_RTC_ENABLE();

    hrtc.Instance = RTC;
    hrtc.Init.HourFormat = RTC_HOURFORMAT_24;
    hrtc.Init.AsynchPrediv = 127;
    hrtc.Init.SynchPrediv  = 249;      // 32000 / (128 * 250) = 1 Hz for a 32 kHz LSI
    hrtc.Init.OutPut = RTC_OUTPUT_DISABLE;
    HAL_RTC_Init(&hrtc);
}

The two prescalers divide the RTC clock down to 1 Hz: (127 + 1) x (249 + 1) = 32000. The real LSI frequency on an STM32F4 is about 32 kHz with a wide tolerance, which the datasheet specifies, so a clock that must be accurate calls for the LSE with the prescalers 127 and 255.

Next the alarm. With every higher field masked, the alarm matches whenever the seconds equal the programmed value, once per minute:

rtc_alarm.cc
static void rtc_set_alarm(uint8_t second)
{
    RTC_AlarmTypeDef a = {0};
    a.AlarmTime.Hours   = 0;
    a.AlarmTime.Minutes = 0;
    a.AlarmTime.Seconds = second;
    a.AlarmMask = RTC_ALARMMASK_DATEWEEKDAY | RTC_ALARMMASK_HOURS | RTC_ALARMMASK_MINUTES;
    a.AlarmSubSecondMask = RTC_ALARMSUBSECONDMASK_ALL;
    a.AlarmDateWeekDaySel = RTC_ALARMDATEWEEKDAYSEL_DATE;
    a.AlarmDateWeekDay = 1;
    a.Alarm = RTC_ALARM_A;
    HAL_RTC_SetAlarm_IT(&hrtc, &a, RTC_FORMAT_BIN);

    HAL_NVIC_SetPriority(RTC_Alarm_IRQn, 5, 0);
    HAL_NVIC_EnableIRQ(RTC_Alarm_IRQn);
}

The masks mean "ignore this field", so only the seconds participate, and the alarm repeats every 60 seconds. The handler vector and the HAL callback complete the interrupt path:

rtc_irq.cc
volatile uint8_t woke_by_alarm;

void RTC_Alarm_IRQHandler(void)
{
    HAL_RTC_AlarmIRQHandler(&hrtc);
}

void HAL_RTC_AlarmAEventCallback(RTC_HandleTypeDef *h)
{
    (void)h;
    woke_by_alarm = 1;
}

Enter Stop and recover

The HAL call that enters Stop takes two arguments: the regulator mode and the entry instruction.

stop_loop.cc
int main(void)
{
    HAL_Init();
    SystemClock_Config();
    gpio_init();
    uart_init();
    rtc_init();
    rtc_set_alarm(0);

    for (;;) {
        printf("measuring\r\n");
        measure_and_send();

        HAL_SuspendTick();
        HAL_PWR_EnterSTOPMode(PWR_LOWPOWERREGULATOR_ON, PWR_STOPENTRY_WFI);

        // execution continues here after the wake-up, running on HSI
        SystemClock_Config();
        HAL_ResumeTick();

        if (woke_by_alarm) {
            woke_by_alarm = 0;
        }
    }
}

HAL_SuspendTick disables the SysTick interrupt. Without it, the tick wakes the core every millisecond and Stop lasts a millisecond. PWR_LOWPOWERREGULATOR_ON puts the internal voltage regulator in its low-power mode during Stop, which saves more current at the price of a longer wake-up. PWR_STOPENTRY_WFI enters with WFI, so the wake-up needs an interrupt. The HAL sets SLEEPDEEP, clears PDDS and then executes WFI, which is exactly the sequence from the register-level description of Stop in the reference manual.

After the wake-up the core runs from the HSI at 16 MHz. This is the line people forget: SystemClock_Config() runs again and reselects HSE and the PLL, restores flash wait states for the high frequency, and puts the bus dividers back. The UART baud rate divisor was computed for the old clock, so the UART must be reconfigured too if its clock changed. With the PLL at 96 MHz and the APB buses unchanged by the HAL's clock function, HAL_UART_Init is only needed when the divisors change, but check by printing a line and reading it on the terminal.

Text
measuring
measuring
measuring
(one line per minute, each after a Stop period)

Clearing the flags

If the chip wakes up immediately each time, a flag from the previous cycle is still set. Two matter. The RTC alarm flag must be cleared, which HAL_RTC_AlarmIRQHandler does when the interrupt runs. And the wake-up flag in PWR->CSR should be cleared before entering Stop:

clear_flags.cc
__HAL_PWR_CLEAR_FLAG(PWR_FLAG_WU);

The HAL's HAL_PWR_EnterSTOPMode already clears the pending EXTI state on some families, but on the F4 you should not assume it, so clear explicitly before the call. Also make sure no other EXTI line has a pending request, such as a button that was bouncing: __HAL_GPIO_EXTI_CLEAR_IT(GPIO_PIN_13) for each line you use.

Measuring that it works

Check the sleep with a current meter, not a debugger. A debugger on the F4 keeps clocks alive in Stop unless the debug bits are cleared, which distorts the result and, when connected, makes it look like Stop works while the chip is actually drawing sleep-mode current plus the debug logic. Run the board from a battery or a bench supply with a series ammeter, with no debug probe attached. A Nucleo board adds the ST-LINK on the same supply, so for realistic numbers you remove the jumper that links the target supply to the debugger, and measure on the target's own supply pin.

The expected shape is a flat low current with a brief increase once per minute for the measurement. If the current stays high, look for the usual suspects: a peripheral clock left on, a GPIO driving a load, the SWD pins in an unexpected state, or the SysTick still running.

Choosing the wake-up source

SourceUse whenHAL call
RTC alarmA fixed time of day or every minuteHAL_RTC_SetAlarm_IT
RTC wake-up timerA fixed interval, independent of time of dayHAL_RTCEx_SetWakeUpTimer_IT
GPIO via EXTIAn external event, such as a buttonHAL_GPIO_Init with GPIO_MODE_IT_*
LPTIMA low-power timer on parts that have oneHAL_LPTIM_*

For a strict period, the wake-up timer is simpler than an alarm, since it reloads itself and has no seconds field to program. The alarm fits tasks tied to the calendar.

When Stop is the wrong mode

If the chip needs to keep a fast peripheral running, for example a UART receiving continuously, Stop is not available: the UART clock is off. If sleep periods are shorter than the wake-up time, you gain nothing, because the chip spends more energy re-starting the oscillator and PLL than it saves. And if the application needs no RAM across the sleep, Standby saves more current, and the next post compares the two.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.