Tips for Using RTC in STM32H5 Microcontrollers

An RTC (Real-Time Clock ) is a specialized timing component used to maintain accurate timekeeping. It is essential in applications where precise, scheduled operations are required. Beyond its use in clocks and watches, RTCs play a critical role in devices like smart meters, washing machines, medicine dispensers, data loggers, and other time-sensitive systems.

STM32 comes with an integrated Real-Time Clock (RTC) that is critical for timekeeping in low-power and secure applications. Whether you are designing data loggers, timestamping critical events, or implementing low-power wake-up strategies, mastering the RTC in STM32H573 can greatly enhance your application reliability.

Unlike general-purpose timers, the RTC operates independently of the main system clock and is part of the backup domain, meaning it can retain time and configuration as long as backup power (usually a coin-cell battery or supercapacitor) is available.

In this blog post, I will share practical tips to help you implement a Real-Time Clock (RTC) in your project using the STM32H573 microcontroller.

 

1. Clock Source Selection (LSE vs LSI):

LSE (Low-Speed External): A 32.768 kHz crystal oscillator. Recommended for accurate timekeeping.

LSI (Low-Speed Internal): Internal RC oscillator (~32 kHz). Lower accuracy, but doesn’t require external components.

Tip: Prefer LSE for calendar/date-based applications. Always check that the crystal startup is stable before proceeding with RTC configuration.

uint32_t timeout = 1000000;
while ((LL_RCC_LSE_IsReady() == 0U) && (--timeout > 0))
{
}

//handle if timeout happen
if (timeout == 0)
{
    // Handle LSE failure, fallback to LSI or error out
}

 

2. Backup Domain Access:

Before configuring the RTC, you must:

  • Enable the power interface clock.
  • Unlock the backup domain by setting the appropriate bits in PWR and RCC registers.
// Example using HAL
__HAL_RCC_RTC_CLK_ENABLE();
LL_PWR_EnableBkUpAccess();

while (LL_PWR_IsEnabledBkUpAccess() != 1U)
{
}
__HAL_RCC_LSEDRIVE_CONFIG(RCC_LSEDRIVE_LOW);
__HAL_RCC_LSE_CONFIG(RCC_LSE_ON);

 

3. Prescaler Configuration:

To get 1 Hz from a 32.768 kHz clock:

  • Asynchronous Prescaler = 127
  • Synchronous Prescaler = 255

These values should be adjusted if you’re using LSI or different clock sources.

 

4. RTC Initialization:

Use the HAL or LL APIs to initialize the RTC only once. On subsequent boots, check the RTC->ISR register or backup register to skip reinitialization.

if (__HAL_RTC_WAKEUPTIMER_GET_FLAG(&hrtc, RTC_FLAG_WUTF) == RESET)
{
    // RTC already initialized, skip init
}

Tip: Use a dedicated backup register to store a “magic value” indicating the RTC is already configured. Example,

const uint32_t BKP_INIT_FLAG = 0x12345;
HAL_RTCEx_BKUPWrite(&hrtc, RTC_BKP_DR0, BKP_INIT_FLAG);

 

5. Using Backup Registers:

The RTC backup domain includes small registers (typically 20) that retain their values during power loss (if VBAT is present).

  • Use them to store flags, timestamps, or configuration values.
  • Available through RTC_BKP_DRx macros.

 

6. Low-Power Mode Integration:

RTC continues running in Standby and Shutdown modes if powered by VBAT.

  • Use RTC alarms or wake-up timers to bring the system out of low-power states.

Tip: Configure the wake-up source properly in PWR and EXTI to ensure the system wakes on time.

 

7. Time and Date Handling:

Use HAL_RTC_SetTime(), HAL_RTC_SetDate(), and the corresponding Get functions to manage the clock.

  • Atomic Time Reads: Always read the date after reading the time and verify that the time register hasn’t rolled over. Better to use built-in HAL consistency mechanism (e.g., HAL_RTC_GetTime() followed by HAL_RTC_GetDate()).
  • Glitch Handling: Add debounce logic when displaying time from user input or external interfaces that poll the RTC.
  • Always validate user input (e.g., for leap years or date overflow).

Tip: Consider converting to a UNIX timestamp for simplified calculations and interoperability.

 

8. Alarm and Wakeup Features:

RTC supports:

  • Alarm A / Alarm B: Triggers interrupts at set time/date.
  • Wake-up Timer: Periodic interrupts independent of date/time.

These features are useful for scheduling tasks or waking the MCU periodically from low-power states.

 

9. Daylight Saving and Drift Correction:

  • STM32 RTC doesn’t handle DST automatically.
  • Use software logic to manage time adjustments. That means implement abstraction over RTC to allow UTC-based storage and conversion to local time zones and daylight saving. This is crucial for global products or data logging across geographies.
  • RTC has a smooth calibration feature to adjust for drift over time. Utilize the RTC smooth calibration registers to fine-tune long-term drift (±487.1 ppm range).
  • External Sync: Periodically sync time from a GPS, GSM/NTP module, or networked interface to re-align drift.

 

10. VBAT Pin Connection:

To retain time during power loss, connect a battery or supercapacitor to the VBAT pin.

Tip: If VBAT is not used, the RTC will lose time on power down unless you’re using a custom power management circuit.

 

11. Handling Reset Conditions:

  • Resetting the RTC or backup domain will erase all RTC settings and time.
  • Always check and restore RTC settings during boot if needed.
  • If firmware corruption resets the RTC settings, add fallback mechanisms to reinitialize safely while preserving logs.

 

12. Debugging and Testing Tips

  • Test LSE oscillator stability using RCC_CSR flags.
  • Use a debugger or UART to print RTC values periodically.
  • Enable RTC interrupt to confirm alarm/wakeup events are working as expected.

 

13. Hardware Design Considerations

  • LSE Crystal Layout: Ensure the 32.768 kHz crystal is placed as close as possible to the MCU with minimal trace length. Avoid vias, use ground shielding, and follow ST’s AN2867 guidelines for crystal design.
  • Load Capacitors: Properly match load capacitors (CL) based on crystal specs and PCB layout parasitics.
  • VBAT Decoupling: Add a decoupling capacitor near the VBAT pin to ensure stability during battery transitions. During transitions, like when switching from main power to backup power (battery/supercapacitor), there may be small voltage dips or spikes. A ceramic capacitor helps absorb these transients and ensures reliable RTC operation without time loss or corruption of backup data.

 

14. Boot-Time Initialization Handling:

  • Avoid Re-initialization: Use a CRC or magic number in backup registers to detect cold boot vs warm boot.
  • Guard Backup Register Corruption: Check backup domain flags or include a checksum with backup register values.

 

15. Low-Power Integration Strategy

  • Real Shutdown Mode Awareness: The STM32H5 supports Shutdown mode where only RTC remains active. Ensure power consumption profiles are within expected thresholds (<1 µA typical).
  • Minimal Wake-up Latency: Profile wake-up time from low-power modes—especially if RTC is used to wake the system for critical tasks.
  • Avoid RTC Drift on LSI: If using LSI (e.g., to save BOM cost), implement periodic calibration using external references (GPS, network sync, etc.).

 

Useful Reference and Link: