STM32 gotchas
199. RTC clock source can be set only once

Source of the clock which drives RTC's time and date counter1 is selected between LSE, HSE/n and LSI in the RTCSEL field in RCC_BDCR register2. As with all other register fields which are in the backup-domain, before accessing it, it is necessary to disable backup-domain protection in PWR_CR.DBP.

However, RCC_BDCR.RTCSEL has an additional constraint: once it has been written to nonzero (zero being the "no RTC clock" default after backup-domain reset), it cannot be rewritten (until another backup-domain reset, either by grounding VBAT pin or through RCC_BDCR.BDRST).

There is an exception to this rule: if LSE is selected as RTC clock, in those newer STM32 families, which have Clock-Security System for LSE (LSECSS), after LSE failure is detected (LSECSSD = 1), RCC_BDCR.RTCSEL can be changed without resetting the whole backup domain.

This all is properly documented in the Reference Manual, but can be easily overlooked.

1.RTC is a typical dual-clock peripheral, having a low-frequency clock for the timekeeping functions and APB clock for register access. Consequences of this arrangement are both delays in accessing some RTC registers, and the shadow registers/lock mechanism in reading out the clock.

2.In 'L0 family, RTCSEL field is not in RCC_BDCR but in RCC_CSR register