embassy_stm32/rtc/
mod.rs

1//! Real Time Clock (RTC)
2mod datetime;
3
4#[cfg(feature = "low-power")]
5mod low_power;
6
7#[cfg(feature = "low-power")]
8use core::cell::Cell;
9
10#[cfg(feature = "low-power")]
11use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
12#[cfg(feature = "low-power")]
13use embassy_sync::blocking_mutex::Mutex;
14
15use self::datetime::{day_of_week_from_u8, day_of_week_to_u8};
16pub use self::datetime::{DateTime, DayOfWeek, Error as DateTimeError};
17use crate::pac::rtc::regs::{Dr, Tr};
18use crate::time::Hertz;
19
20/// refer to AN4759 to compare features of RTC2 and RTC3
21#[cfg_attr(any(rtc_v1), path = "v1.rs")]
22#[cfg_attr(
23    any(
24        rtc_v2f0, rtc_v2f2, rtc_v2f3, rtc_v2f4, rtc_v2f7, rtc_v2h7, rtc_v2l0, rtc_v2l1, rtc_v2l4, rtc_v2wb
25    ),
26    path = "v2.rs"
27)]
28#[cfg_attr(any(rtc_v3, rtc_v3u5, rtc_v3l5, rtc_v3h7rs, rtc_v3c0), path = "v3.rs")]
29mod _version;
30#[allow(unused_imports)]
31pub use _version::*;
32
33use crate::peripherals::RTC;
34use crate::Peri;
35
36/// Errors that can occur on methods on [RtcClock]
37#[non_exhaustive]
38#[derive(Clone, Debug, PartialEq, Eq)]
39#[cfg_attr(feature = "defmt", derive(defmt::Format))]
40pub enum RtcError {
41    /// An invalid DateTime was given or stored on the hardware.
42    InvalidDateTime(DateTimeError),
43
44    /// The current time could not be read
45    ReadFailure,
46
47    /// The RTC clock is not running
48    NotRunning,
49}
50
51/// Provides immutable access to the current time of the RTC.
52pub struct RtcTimeProvider {
53    _private: (),
54}
55
56impl RtcTimeProvider {
57    /// Return the current datetime.
58    ///
59    /// # Errors
60    ///
61    /// Will return an `RtcError::InvalidDateTime` if the stored value in the system is not a valid [`DayOfWeek`].
62    pub fn now(&self) -> Result<DateTime, RtcError> {
63        self.read(|dr, tr, _ss| {
64            let second = bcd2_to_byte((tr.st(), tr.su()));
65            let minute = bcd2_to_byte((tr.mnt(), tr.mnu()));
66            let hour = bcd2_to_byte((tr.ht(), tr.hu()));
67
68            let weekday = day_of_week_from_u8(dr.wdu()).map_err(RtcError::InvalidDateTime)?;
69            let day = bcd2_to_byte((dr.dt(), dr.du()));
70            let month = bcd2_to_byte((dr.mt() as u8, dr.mu()));
71            let year = bcd2_to_byte((dr.yt(), dr.yu())) as u16 + 2000_u16;
72
73            // Calculate second fraction and multiply to microseconds
74            // Formula from RM0410
75            #[cfg(not(rtc_v2f2))]
76            let us = {
77                let prediv = RTC::regs().prer().read().prediv_s() as f32;
78                (((prediv - _ss as f32) / (prediv + 1.0)) * 1e6).min(999_999.0) as u32
79            };
80            #[cfg(rtc_v2f2)]
81            let us = 0;
82
83            DateTime::from(year, month, day, weekday, hour, minute, second, us).map_err(RtcError::InvalidDateTime)
84        })
85    }
86
87    fn read<R>(&self, mut f: impl FnMut(Dr, Tr, u16) -> Result<R, RtcError>) -> Result<R, RtcError> {
88        let r = RTC::regs();
89
90        #[cfg(not(rtc_v2f2))]
91        let read_ss = || r.ssr().read().ss();
92        #[cfg(rtc_v2f2)]
93        let read_ss = || 0;
94
95        let mut ss = read_ss();
96        for _ in 0..5 {
97            let tr = r.tr().read();
98            let dr = r.dr().read();
99            let ss_after = read_ss();
100
101            // If an RTCCLK edge occurs during read we may see inconsistent values
102            // so read ssr again and see if it has changed. (see RM0433 Rev 7 46.3.9)
103            if ss == ss_after {
104                return f(dr, tr, ss.try_into().unwrap());
105            } else {
106                ss = ss_after
107            }
108        }
109
110        Err(RtcError::ReadFailure)
111    }
112}
113
114/// RTC driver.
115pub struct Rtc {
116    #[cfg(feature = "low-power")]
117    stop_time: Mutex<CriticalSectionRawMutex, Cell<Option<low_power::RtcInstant>>>,
118    _private: (),
119}
120
121/// RTC configuration.
122#[non_exhaustive]
123#[derive(Copy, Clone, PartialEq)]
124pub struct RtcConfig {
125    /// The subsecond counter frequency; default is 256
126    ///
127    /// A high counter frequency may impact stop power consumption
128    pub frequency: Hertz,
129}
130
131impl Default for RtcConfig {
132    /// LSI with prescalers assuming 32.768 kHz.
133    /// Raw sub-seconds in 1/256.
134    fn default() -> Self {
135        RtcConfig { frequency: Hertz(256) }
136    }
137}
138
139/// Calibration cycle period.
140#[derive(Default, Copy, Clone, Debug, PartialEq)]
141#[repr(u8)]
142pub enum RtcCalibrationCyclePeriod {
143    /// 8-second calibration period
144    Seconds8,
145    /// 16-second calibration period
146    Seconds16,
147    /// 32-second calibration period
148    #[default]
149    Seconds32,
150}
151
152impl Rtc {
153    /// Create a new RTC instance.
154    pub fn new(_rtc: Peri<'static, RTC>, rtc_config: RtcConfig) -> Self {
155        #[cfg(not(any(stm32l0, stm32f3, stm32l1, stm32f0, stm32f2)))]
156        crate::rcc::enable_and_reset::<RTC>();
157
158        let mut this = Self {
159            #[cfg(feature = "low-power")]
160            stop_time: Mutex::const_new(CriticalSectionRawMutex::new(), Cell::new(None)),
161            _private: (),
162        };
163
164        let frequency = Self::frequency();
165        let async_psc = ((frequency.0 / rtc_config.frequency.0) - 1) as u8;
166        let sync_psc = (rtc_config.frequency.0 - 1) as u16;
167
168        this.configure(async_psc, sync_psc);
169
170        // Wait for the clock to update after initialization
171        #[cfg(not(rtc_v2f2))]
172        {
173            let now = this.time_provider().read(|_, _, ss| Ok(ss)).unwrap();
174            while now == this.time_provider().read(|_, _, ss| Ok(ss)).unwrap() {}
175        }
176
177        this
178    }
179
180    fn frequency() -> Hertz {
181        let freqs = unsafe { crate::rcc::get_freqs() };
182        freqs.rtc.to_hertz().unwrap()
183    }
184
185    /// Acquire a [`RtcTimeProvider`] instance.
186    pub const fn time_provider(&self) -> RtcTimeProvider {
187        RtcTimeProvider { _private: () }
188    }
189
190    /// Set the datetime to a new value.
191    ///
192    /// # Errors
193    ///
194    /// Will return `RtcError::InvalidDateTime` if the datetime is not a valid range.
195    pub fn set_datetime(&mut self, t: DateTime) -> Result<(), RtcError> {
196        self.write(true, |rtc| {
197            let (ht, hu) = byte_to_bcd2(t.hour());
198            let (mnt, mnu) = byte_to_bcd2(t.minute());
199            let (st, su) = byte_to_bcd2(t.second());
200
201            let (dt, du) = byte_to_bcd2(t.day());
202            let (mt, mu) = byte_to_bcd2(t.month());
203            let yr = t.year();
204            let yr_offset = (yr - 2000_u16) as u8;
205            let (yt, yu) = byte_to_bcd2(yr_offset);
206
207            use crate::pac::rtc::vals::Ampm;
208
209            rtc.tr().write(|w| {
210                w.set_ht(ht);
211                w.set_hu(hu);
212                w.set_mnt(mnt);
213                w.set_mnu(mnu);
214                w.set_st(st);
215                w.set_su(su);
216                w.set_pm(Ampm::AM);
217            });
218
219            rtc.dr().write(|w| {
220                w.set_dt(dt);
221                w.set_du(du);
222                w.set_mt(mt > 0);
223                w.set_mu(mu);
224                w.set_yt(yt);
225                w.set_yu(yu);
226                w.set_wdu(day_of_week_to_u8(t.day_of_week()));
227            });
228        });
229
230        Ok(())
231    }
232
233    /// Return the current datetime.
234    ///
235    /// # Errors
236    ///
237    /// Will return an `RtcError::InvalidDateTime` if the stored value in the system is not a valid [`DayOfWeek`].
238    pub fn now(&self) -> Result<DateTime, RtcError> {
239        self.time_provider().now()
240    }
241
242    /// Check if daylight savings time is active.
243    pub fn get_daylight_savings(&self) -> bool {
244        let cr = RTC::regs().cr().read();
245        cr.bkp()
246    }
247
248    /// Enable/disable daylight savings time.
249    pub fn set_daylight_savings(&mut self, daylight_savings: bool) {
250        self.write(true, |rtc| {
251            rtc.cr().modify(|w| w.set_bkp(daylight_savings));
252        })
253    }
254
255    /// Number of backup registers of this instance.
256    pub const BACKUP_REGISTER_COUNT: usize = RTC::BACKUP_REGISTER_COUNT;
257
258    /// Read content of the backup register.
259    ///
260    /// The registers retain their values during wakes from standby mode or system resets. They also
261    /// retain their value when Vdd is switched off as long as V_BAT is powered.
262    pub fn read_backup_register(&self, register: usize) -> Option<u32> {
263        RTC::read_backup_register(RTC::regs(), register)
264    }
265
266    /// Set content of the backup register.
267    ///
268    /// The registers retain their values during wakes from standby mode or system resets. They also
269    /// retain their value when Vdd is switched off as long as V_BAT is powered.
270    pub fn write_backup_register(&self, register: usize, value: u32) {
271        RTC::write_backup_register(RTC::regs(), register, value)
272    }
273}
274
275pub(crate) fn byte_to_bcd2(byte: u8) -> (u8, u8) {
276    let mut bcd_high: u8 = 0;
277    let mut value = byte;
278
279    while value >= 10 {
280        bcd_high += 1;
281        value -= 10;
282    }
283
284    (bcd_high, ((bcd_high << 4) | value))
285}
286
287pub(crate) fn bcd2_to_byte(bcd: (u8, u8)) -> u8 {
288    let value = bcd.1 | bcd.0 << 4;
289
290    let tmp = ((value & 0xF0) >> 0x4) * 10;
291
292    tmp + (value & 0x0F)
293}
294
295trait SealedInstance {
296    const BACKUP_REGISTER_COUNT: usize;
297
298    #[cfg(feature = "low-power")]
299    #[cfg(not(any(stm32wba, stm32u5, stm32u0)))]
300    const EXTI_WAKEUP_LINE: usize;
301
302    #[cfg(feature = "low-power")]
303    type WakeupInterrupt: crate::interrupt::typelevel::Interrupt;
304
305    fn regs() -> crate::pac::rtc::Rtc {
306        crate::pac::RTC
307    }
308
309    /// Read content of the backup register.
310    ///
311    /// The registers retain their values during wakes from standby mode or system resets. They also
312    /// retain their value when Vdd is switched off as long as V_BAT is powered.
313    fn read_backup_register(rtc: crate::pac::rtc::Rtc, register: usize) -> Option<u32>;
314
315    /// Set content of the backup register.
316    ///
317    /// The registers retain their values during wakes from standby mode or system resets. They also
318    /// retain their value when Vdd is switched off as long as V_BAT is powered.
319    fn write_backup_register(rtc: crate::pac::rtc::Rtc, register: usize, value: u32);
320
321    // fn apply_config(&mut self, rtc_config: RtcConfig);
322}