stm32f429_hal/
watchdog.rs

1//! Watchdog peripherals
2
3use stm32f429::IWDG;
4
5/// Watchdogs will reset your device if it fails reloading them.
6pub trait Watchdog {
7    /// Write reload value to watchdog
8    fn reload(&mut self);
9}
10
11/// Wraps the Independent Watchdog (IWDG) peripheral
12pub struct IndependentWatchdog {
13    iwdg: IWDG,
14}
15
16const MAX_PR: u8 = 6;
17const MAX_RL: u16 = 0xFFF;
18const KR_ACCESS: u16 = 0x5555;
19const KR_RELOAD: u16 = 0xAAAA;
20const KR_START: u16 = 0xCCCC;
21
22
23impl IndependentWatchdog {
24    /// Wrap and start the watchdog
25    pub fn new(iwdg: IWDG, timeout_ms: u32) -> Self {
26        IndependentWatchdog { iwdg }
27            .setup(timeout_ms)
28    }
29
30    fn setup(self, timeout_ms: u32) -> Self {
31        let mut pr = 0;
32        while pr < MAX_PR && Self::timeout_period(pr, MAX_RL) < timeout_ms {
33            pr += 1;
34        }
35
36        let max_period = Self::timeout_period(pr, MAX_RL);
37        let max_rl = u32::from(MAX_RL);
38        let rl = (timeout_ms * max_rl / max_period).min(max_rl) as u16;
39
40        self.access_registers(|iwdg| {
41            iwdg.pr.modify(|_,w| unsafe { w.pr().bits(pr) });
42            iwdg.rlr.modify(|_, w| unsafe { w.rl().bits(rl) });
43        });
44        self.iwdg.kr.write(|w| unsafe { w.key().bits(KR_START) });
45
46        self
47    }
48
49    fn is_pr_updating(&self) -> bool {
50        self.iwdg.sr.read().pvu().bit()
51    }
52
53    /// Returns the interval in ms
54    pub fn interval(&self) -> u32 {
55        while self.is_pr_updating() {}
56
57        let pr = self.iwdg.pr.read().pr().bits();
58        let rl = self.iwdg.rlr.read().rl().bits();
59        Self::timeout_period(pr, rl)
60    }
61
62    /// pr: Prescaler divider bits, rl: reload value
63    ///
64    /// Returns ms
65    fn timeout_period(pr: u8, rl: u16) -> u32 {
66        let divider: u32 = [4, 8, 16, 32, 64, 128, 256][usize::from(pr)];
67        (u32::from(rl) + 1) * divider / 32
68    }
69
70    fn access_registers<A, F: FnMut(&IWDG) -> A>(&self, mut f: F) -> A {
71        // Unprotect write access to registers
72        self.iwdg.kr.write(|w| unsafe { w.key().bits(KR_ACCESS) });
73        let a = f(&self.iwdg);
74
75        // Protect again
76        // self.iwdg.kr.write(|w| unsafe { w.key().bits(KR_RELOAD) });
77        a
78    }
79}
80
81impl Watchdog for IndependentWatchdog {
82    fn reload(&mut self) {
83        self.iwdg.kr.write(|w| unsafe { w.key().bits(KR_RELOAD) });
84    }
85}