Skip to main content

ch32_hal/
rtc.rs

1//! Real-time clock (RTC).
2//!
3//! A 32-bit seconds counter with a 20-bit prescaler and one alarm compare
4//! register (RM §6.1). The counter and prescaler sit in the backup domain, so
5//! they keep running across system resets while VBAT is present and dropping
6//! the handle does not stop the clock (RM §6.2.2).
7//!
8//! [`Rtc::new`] enables the requested oscillator, selects it as `RTCCLK` and
9//! writes the prescaler for a 1 Hz time base (RM §3.3.5.3). If the RTC is
10//! already running from the same source, it is left as it is: counter and
11//! prescaler are kept, so the elapsed time is preserved.
12//!
13//! Register writes go through the configuration sequence of RM §6.2.3: poll
14//! `CTLRL.RTOFF`, set `CNF`, write, clear `CNF`, poll `RTOFF`.
15
16use crate::pac::rcc::vals::Rtcsel;
17use crate::time::Hertz;
18use crate::{pac, peripherals, Peri};
19
20/// Source of the 1 Hz RTC time base.
21#[derive(Copy, Clone, PartialEq, Eq)]
22pub enum ClockSource {
23    /// Internal ~40 kHz RC oscillator. Always available, but its frequency is
24    /// only nominal, so expect drift of a few percent.
25    Lsi,
26    /// External 32.768 kHz crystal on the OSC32 pins, or a square wave fed
27    /// into OSC32_IN when `bypass` is set.
28    Lse { frequency: Hertz, bypass: bool },
29    /// HSE divided by 512. The HSE tree must already be running.
30    #[cfg(rcc_h4)]
31    HseDiv512 { frequency: Hertz },
32}
33
34/// RTC configuration error.
35#[derive(Debug, Copy, Clone, PartialEq, Eq)]
36#[cfg_attr(feature = "defmt", derive(defmt::Format))]
37pub enum Error {
38    /// The RTC is already running from another source. Retargeting it would
39    /// silently change the time base, so the constructor refuses to do so.
40    ClockSourceMismatch,
41    /// `frequency - 1` does not fit the 20-bit prescaler.
42    InvalidFrequency(Hertz),
43}
44
45impl ClockSource {
46    fn rtcsel(self) -> Rtcsel {
47        match self {
48            Self::Lsi => Rtcsel::LSI,
49            Self::Lse { .. } => Rtcsel::LSE,
50            #[cfg(rcc_h4)]
51            Self::HseDiv512 { .. } => Rtcsel::HSE_DIV512,
52        }
53    }
54
55    fn frequency(self) -> Hertz {
56        match self {
57            Self::Lsi => crate::rcc::LSI_FREQ,
58            Self::Lse { frequency, .. } => frequency,
59            #[cfg(rcc_h4)]
60            Self::HseDiv512 { frequency } => frequency / 512u32,
61        }
62    }
63
64    /// Start the oscillator and wait until it is ready.
65    fn enable(self) {
66        let rcc = pac::RCC;
67        match self {
68            Self::Lsi => {
69                // LSION lives in RSTSCKR, outside the write-protected backup
70                // block (RM §3.4.11).
71                rcc.rstsckr().modify(|w| w.set_lsion(true));
72                while !rcc.rstsckr().read().lsirdy() {}
73            }
74            Self::Lse { bypass, .. } => {
75                // `LSEBYP` may only change while `LSEON` is clear (RM §3.4.10).
76                // Leave a running oscillator alone, including its bypass mode.
77                if !rcc.bdctlr().read().lseon() {
78                    // One write: a second read-modify-write can read back a
79                    // stale `BDCTLR` and drop this bit again.
80                    rcc.bdctlr().modify(|w| {
81                        w.set_lsebyp(bypass);
82                        w.set_lseon(true);
83                    });
84                }
85                while !rcc.bdctlr().read().lserdy() {}
86            }
87            #[cfg(rcc_h4)]
88            Self::HseDiv512 { .. } => {}
89        }
90    }
91}
92
93/// RTC handle. The clock keeps counting after this is dropped.
94pub struct Rtc<'d> {
95    _peri: Peri<'d, peripherals::RTC>,
96    frequency: Hertz,
97}
98
99impl<'d> Rtc<'d> {
100    /// Enable the RTC from `source` with a 1 Hz time base.
101    ///
102    /// An RTC already running from `source` keeps the prescaler it was
103    /// started with: the prescaler is write-only, and rewriting it restarts
104    /// the current second.
105    ///
106    /// Returns an error before changing `RTCCLK` when the divider does not
107    /// fit or the RTC already runs from another source.
108    pub fn new(peri: Peri<'d, peripherals::RTC>, source: ClockSource) -> Result<Self, Error> {
109        let frequency = source.frequency();
110        let divider = match frequency.0.checked_sub(1) {
111            Some(divider) if divider <= 0x000F_FFFF => divider,
112            _ => return Err(Error::InvalidFrequency(frequency)),
113        };
114
115        crate::rcc::ls::enable_backup_domain_writes();
116
117        let bdctlr = pac::RCC.bdctlr();
118        let rtcsel = source.rtcsel();
119        let current = bdctlr.read().rtcsel();
120        // `RTCEN` can be left set with `RTCSEL = NO_CLK`; that is not a
121        // running clock, so it is safe to pick a source again.
122        let running = bdctlr.read().rtcen() && current != Rtcsel::NO_CLK;
123        if running && current != rtcsel {
124            return Err(Error::ClockSourceMismatch);
125        }
126
127        source.enable();
128
129        if !running {
130            // Select the source and enable the clock in one write. Split
131            // read-modify-writes race the backup-domain update: the second
132            // read can return the old `RTCSEL` and clear it again.
133            bdctlr.modify(|w| {
134                w.set_rtcsel(rtcsel);
135                w.set_rtcen(true);
136            });
137        }
138
139        let rtc = Self { _peri: peri, frequency };
140        // First access after a reset must re-acquire the register shadow
141        // (RM §6.3.2).
142        rtc.synchronize();
143        // Program the divider only on a stopped RTC: writing it while the
144        // RTC runs restarts the current second, so every re-open would lose
145        // up to one second.
146        if !running {
147            rtc.write_prescaler(divider);
148        }
149        Ok(rtc)
150    }
151
152    /// Clock frequency fed into the prescaler.
153    pub fn frequency(&self) -> Hertz {
154        self.frequency
155    }
156
157    /// Re-acquire the register shadow after Stop-mode wake-up or an HB reset.
158    ///
159    /// Clearing `RSF` and waiting for hardware to set it again makes the
160    /// prescaler, alarm and counter reads current (RM §6.3.2).
161    pub fn synchronize(&self) {
162        let ctlrl = pac::RTC.ctlrl();
163        ctlrl.modify(|w| w.set_rsf(false));
164        while !ctlrl.read().rsf() {}
165    }
166
167    /// Current counter value in seconds. The epoch is whatever the user set.
168    pub fn get_time(&self) -> u32 {
169        let rtc = pac::RTC;
170        // CNTH changes once per 65536 s, but re-read it so a wrap between the
171        // two accesses cannot produce a torn value.
172        loop {
173            let high = rtc.cnth().read().cnth();
174            let low = rtc.cntl().read().cntl();
175            if rtc.cnth().read().cnth() == high {
176                return (u32::from(high) << 16) | u32::from(low);
177            }
178        }
179    }
180
181    /// Write the counter. Takes effect on the next prescaler tick.
182    pub fn set_time(&self, seconds: u32) {
183        let rtc = pac::RTC;
184        self.enter_config();
185        // The low word write commits the pair.
186        rtc.cnth().write(|w| w.set_cnth((seconds >> 16) as u16));
187        rtc.cntl().write(|w| w.set_cntl(seconds as u16));
188        self.exit_config();
189    }
190
191    /// Set the alarm compare value.
192    ///
193    /// A pending `ALRF` is cleared first so a stale match cannot fire the
194    /// interrupt for the new value.
195    pub fn set_alarm(&self, seconds: u32) {
196        let rtc = pac::RTC;
197        self.clear_alarm_flag();
198        self.enter_config();
199        rtc.alrmh().write(|w| w.set_alrh((seconds >> 16) as u16));
200        rtc.alrml().write(|w| w.set_alrl(seconds as u16));
201        self.exit_config();
202    }
203
204    /// Current prescaler counter. It counts down from `frequency - 1` to 0;
205    /// two reads one tick apart differ while `RTCCLK` is alive.
206    pub fn read_prescaler(&self) -> u32 {
207        let rtc = pac::RTC;
208        (u32::from(rtc.divh().read().divh()) << 16) | u32::from(rtc.divl().read().divl())
209    }
210
211    /// Second-event interrupt on the `RTC` vector.
212    pub fn enable_second_interrupt(&self, enable: bool) {
213        pac::RTC.ctlrh().modify(|w| w.set_secie(enable));
214    }
215
216    /// Alarm interrupt on the `RTCALARM` vector.
217    pub fn enable_alarm_interrupt(&self, enable: bool) {
218        pac::RTC.ctlrh().modify(|w| w.set_alrie(enable));
219    }
220
221    /// Overflow interrupt on the `RTC` vector.
222    pub fn enable_overflow_interrupt(&self, enable: bool) {
223        pac::RTC.ctlrh().modify(|w| w.set_owie(enable));
224    }
225
226    /// A second elapsed since the last clear.
227    pub fn second_flag(&self) -> bool {
228        pac::RTC.ctlrl().read().secf()
229    }
230
231    /// The counter reached the alarm value.
232    pub fn alarm_flag(&self) -> bool {
233        pac::RTC.ctlrl().read().alrf()
234    }
235
236    /// The 32-bit counter wrapped.
237    pub fn overflow_flag(&self) -> bool {
238        pac::RTC.ctlrl().read().owf()
239    }
240
241    /// Clear the second-event flag.
242    pub fn clear_second_flag(&self) {
243        pac::RTC.ctlrl().modify(|w| w.set_secf(false));
244    }
245
246    /// Clear the alarm flag.
247    pub fn clear_alarm_flag(&self) {
248        pac::RTC.ctlrl().modify(|w| w.set_alrf(false));
249    }
250
251    /// Clear the overflow flag.
252    pub fn clear_overflow_flag(&self) {
253        pac::RTC.ctlrl().modify(|w| w.set_owf(false));
254    }
255
256    /// Clear `SECF`, `ALRF` and `OWF` in one write.
257    pub fn clear_flags(&self) {
258        pac::RTC.ctlrl().modify(|w| {
259            w.set_secf(false);
260            w.set_alrf(false);
261            w.set_owf(false);
262        });
263    }
264
265    fn write_prescaler(&self, divider: u32) {
266        self.enter_config();
267        // High word first; the low word commits the divider.
268        pac::RTC.pscrh().write(|w| w.set_prlh((divider >> 16) as u8));
269        pac::RTC.pscrl().write(|w| w.set_prll(divider as u16));
270        self.exit_config();
271    }
272
273    fn enter_config(&self) {
274        let ctlrl = pac::RTC.ctlrl();
275        while !ctlrl.read().rtoff() {}
276        ctlrl.modify(|w| w.set_cnf(true));
277    }
278
279    fn exit_config(&self) {
280        let ctlrl = pac::RTC.ctlrl();
281        ctlrl.modify(|w| w.set_cnf(false));
282        while !ctlrl.read().rtoff() {}
283    }
284}