Skip to main content

ch32_hal/rcc/
ls.rs

1//! LSE / LSI / RTC clock setup (RCC_BDCTLR).
2
3use crate::pac::rcc::vals::Rtcsel;
4use crate::pac::RCC;
5use crate::rcc::{LsConfig, LseMode, RtcClockSource, LSI_FREQ};
6use crate::time::Hertz;
7
8/// `RTCSEL` value for the divided HSE: /512 on CH32H4; /128 or /512 on
9/// V2/V3, depending on the part (RCC_BDCTLR).
10#[cfg(rcc_h4)]
11const RTCSEL_HSE: Rtcsel = Rtcsel::HSE_DIV512;
12#[cfg(pwr_v3)]
13const RTCSEL_HSE: Rtcsel = Rtcsel::HSE;
14
15/// Allow writes to the backup domain (`RCC_BDCTLR`, RTC, BKP).
16///
17/// LSEON, LSEBYP, RTCSEL and RTCEN live in the write-protected backup
18/// domain: writes are dropped until `PWR.CTLR.DBP` is set, and PWR itself
19/// needs its bus clock (RCC_BDCTLR in the reference manuals).
20pub(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            // One write: a second read-modify-write can read back a stale
39            // `BDCTLR` and drop `LSEBYP` again.
40            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    // Never retarget a running RTC: its counter would silently change time
68    // base while the prescaler keeps the old divider.
69    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}