stm32f429_hal/
watchdog.rs1use stm32f429::IWDG;
4
5pub trait Watchdog {
7 fn reload(&mut self);
9}
10
11pub 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 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 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 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 self.iwdg.kr.write(|w| unsafe { w.key().bits(KR_ACCESS) });
73 let a = f(&self.iwdg);
74
75 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}