1use crate::pac::rcc::vals::Rtcsel;
4use crate::pac::RCC;
5use crate::rcc::{LsConfig, LseMode, RtcClockSource, LSI_FREQ};
6use crate::time::Hertz;
7
8#[cfg(rcc_h4)]
11const RTCSEL_HSE: Rtcsel = Rtcsel::HSE_DIV512;
12#[cfg(pwr_v3)]
13const RTCSEL_HSE: Rtcsel = Rtcsel::HSE;
14
15pub(crate) fn enable_backup_domain_writes() {
21 #[cfg(rcc_h4)]
22 RCC.hb1pcenr().modify(|w| w.set_pwren(true));
23 #[cfg(pwr_v3)]
24 RCC.apb1pcenr().modify(|w| w.set_pwren(true));
25 crate::pac::PWR.ctlr().modify(|w| w.set_dbp(true));
26}
27
28pub(crate) unsafe fn init_ls(config: &LsConfig) -> Option<Hertz> {
29 enable_backup_domain_writes();
30
31 if config.lsi {
32 RCC.rstsckr().modify(|w| w.set_lsion(true));
33 while !RCC.rstsckr().read().lsirdy() {}
34 }
35
36 let lse_hz = match &config.lse {
37 Some(lse) => {
38 RCC.bdctlr().modify(|w| {
41 w.set_lsebyp(lse.mode == LseMode::Bypass);
42 w.set_lseon(true);
43 });
44 while !RCC.bdctlr().read().lserdy() {}
45 Some(lse.frequency)
46 }
47 None => None,
48 };
49
50 let rtcsel = match config.rtc {
51 RtcClockSource::DISABLE => Rtcsel::NO_CLK,
52 RtcClockSource::LSE => {
53 if lse_hz.is_none() {
54 panic!("RCC: RTC clock source LSE requires `Config.ls.lse`");
55 }
56 Rtcsel::LSE
57 }
58 RtcClockSource::LSI => {
59 if !config.lsi {
60 panic!("RCC: RTC clock source LSI requires `Config.ls.lsi = true`");
61 }
62 Rtcsel::LSI
63 }
64 RtcClockSource::HSE => RTCSEL_HSE,
65 };
66
67 if !RCC.bdctlr().read().rtcen() || rtcsel == Rtcsel::NO_CLK {
70 RCC.bdctlr().modify(|w| w.set_rtcsel(rtcsel));
71 }
72
73 match rtcsel {
74 Rtcsel::LSE => lse_hz,
75 Rtcsel::LSI => Some(LSI_FREQ),
76 _ => None,
77 }
78}