Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Configuring STM32 RTC and Backup Power Registers

Tech 1

Backup Registers (BKP) Architecture

The BKP module offers non-volatile storage solutions that retain data even when the main power supply (VDD) is interrupted. Information remains intact provided the backup voltage rail (VBAT) stays within 1.8V–3.6V. System resets, wake-ups from standby mode, or power-on resets will not erase this content; however, activating the TAMPER pin immediately wipes all stored data.

Besides user-defined storage, this area holds specific values for RTC calibration. Memory capacity varies by device family: low/medium-density chips provide 20 bytes, while high-density and connectivity lines offer up to 84 bytes.

Access Control Requirements

Interfacing with the BKP requires enabling specific gating bits in the Peripheral Clock and Power registers. The DBP bit in the PWR control register must be set to allow writes to the backup domain. Furthermore, clocks for both the PWR and BKP modules on the APB1 bus must be enabled via RCC_APB1PeriphClockCmd. Skipping these steps locks access to prevent accidental overwrites during boot sequences.

Real-Time Clock (RTC) Overview

The RTC functions as a standalone timer peripheral capable of tracking time-of-day and calender dates independently of the CPU core. It utilizes a 32-bit programmable counter paired with a 20-bit prescaler to generate system time bases. Three interrupt source are available:

  • Alarm Interrupt: Triggered when the internal counter matches the alarm register value.
  • Second Interrupt: Generates a periodic pulse at a fixed rate (typically 1 second).
  • Overflow Interrupt: Signals when the internal counter wraps around to zero.

Clock Source Selection

Three primary clock inputs drive the RTC core:

  1. HSE Divider: External High-Speed crystal divided by 128 (e.g., 8MHz / 128).
  2. LSE Crystal: Low-Speed External oscillator (standard 32.768 kHz).
  3. LSI Oscillator: Internal Low-Speed RC oscillator (~40 kHz).

Critical Note: Only the LSE source supports continuous operation powered solely by VBAT. Using LSI or HSE means the RTC counts will pause if main power (VDD) is lost. For applications requiring persistent timekeeping across power cycles, LSE is mandatory.

Initialization Protocols

Correct interaction with RTC registers demands strict sequencing to avoid synchronization errors:

  • Synchronization Check: After enabling the interface, poll the RSF flag in the status register to confirm the hardware has caught up with software writes.
  • Configuration Lock: Set the CNF bit before modifying the Prescaler (PRL), Counter (CNT), or Alarm (ALR) registers. Clear it after configuration.
  • Write Safety: Always verify the RTOFF status bit. If cleared, the RTC is current updating counters and cannot accept new values. Polling ensures stability before writing.
#include "stm32f10x_rcc.h"
#include "stm32f10x_pwr.h"
#include "stm32f10x_bkp.h"
#include "stm32f10x_rtc.h"

#define CONFIG_MARKER  0xBEEF

void init_RTC_Core(void)
{
    uint16_t boot_status;

    /* Enable Clocks for Power and Backup Domains */
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_PWR | RCC_APB1Periph_BKP, ENABLE);

    /* Unlock Backup Access Domain */
    PWR_BackupAccessCmd(ENABLE);

    /* Detect First Boot Sequence */
    boot_status = BKP_ReadBackupRegister(BKP_DR1);

    if (boot_status != CONFIG_MARKER)
    {
        /* Initial Configuration Block */
        
        /* Configure Clock Source (LSE preferred for retention) */
        RCC_LSEConfig(RCC_LSE_ON);
        while (RCC_GetFlagStatus(RCC_FLAG_LSERDY) == RESET);
        
        RCC_RTCCLKConfig(RCC_RTCCLKSource_LSE);
        RCC_RTCCLKCmd(ENABLE);

        /* Ensure Hardware Sync Before Writes */
        RTC_WaitForSynchro();
        RTC_WaitForLastTask();

        /* Set Prescaler for 1Hz Output (32768 - 1) */
        RTC_SetPrescaler(32767);
        RTC_WaitForLastTask();

        /* Write Custom Time Values */
        configure_Time_Values();

        /* Save Magic Number for Subsequent Boots */
        BKP_WriteBackupRegister(BKP_DR1, CONFIG_MARKER);
    }
    else
    {
        /* Subsequent Boot: Skip Config, Ensure Clock Running */
        RTC_WaitForSynchro();
        RTC_WaitForLastTask();
        RCC_LSEConfig(RCC_LSE_ON);
        while (RCC_GetFlagStatus(RCC_FLAG_LSERDY) == RESET);
        RCC_RTCCLKConfig(RCC_RTCCLKSource_LSE);
        RCC_RTCCLKCmd(ENABLE);
    }
}

/* Placeholder for setting hour/minute/second */
void configure_Time_Values(void)
{
    RTC_SetCounter(0x00000000);
}

Schematic Considerations

When designing custom PCBs, ensure the LSE crystal network adheres closely to manufacturer load capacitor guidelines. Place decoupling capacitors near the VBAT pin to maintain impedance stability during power transitions. For high-reliability implementations, consider adding isolation diodes between external battery sources and the internal power rails.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.