stm32f7x7_hal/
watchdog.rs1use crate::{
4 stm32::{IWDG, DBGMCU},
5 hal::watchdog::{Watchdog, WatchdogEnable},
6 time::MilliSeconds,
7};
8
9pub struct IndependentWatchdog {
11 iwdg: IWDG,
12}
13
14const MAX_PR: u8 = 0b110;
15const MAX_RL: u16 = 0xFFF;
16const KR_ACCESS: u16 = 0x5555;
17const KR_RELOAD: u16 = 0xAAAA;
18const KR_START: u16 = 0xCCCC;
19
20
21impl IndependentWatchdog {
22 pub fn new(iwdg: IWDG) -> Self {
24 IndependentWatchdog { iwdg }
25 }
26
27 pub fn stop_on_debug(&self, dbgmcu: &DBGMCU, stop: bool) {
29 dbgmcu.apb1_fz.modify(|_, w| w.dbg_iwdg_stop().bit(stop));
30 }
31
32 fn setup(&self, timeout_ms: u32) {
33 let mut pr = 0;
34 while pr < MAX_PR && Self::timeout_period(pr, MAX_RL) < timeout_ms {
35 pr += 1;
36 }
37
38 let max_period = Self::timeout_period(pr, MAX_RL);
39 let max_rl = u32::from(MAX_RL);
40 let rl = (timeout_ms * max_rl / max_period).min(max_rl) as u16;
41
42 self.access_registers(|iwdg| {
43 iwdg.pr.modify(|_,w| w.pr().bits(pr));
44 iwdg.rlr.modify(|_, w| w.rl().bits(rl));
45 });
46 }
47
48 fn is_pr_updating(&self) -> bool {
49 self.iwdg.sr.read().pvu().bit()
50 }
51
52 pub fn interval(&self) -> MilliSeconds {
54 while self.is_pr_updating() {}
55
56 let pr = self.iwdg.pr.read().pr().bits();
57 let rl = self.iwdg.rlr.read().rl().bits();
58 let ms = Self::timeout_period(pr, rl);
59 MilliSeconds(ms)
60 }
61
62 fn timeout_period(pr: u8, rl: u16) -> u32 {
66 let divider: u32 = match pr {
67 0b000 => 4,
68 0b001 => 8,
69 0b010 => 16,
70 0b011 => 32,
71 0b100 => 64,
72 0b101 => 128,
73 0b110 => 256,
74 0b111 => 256,
75 _ => unreachable!(),
76 };
77 (u32::from(rl) + 1) * divider / 32
78 }
79
80 fn access_registers<A, F: FnMut(&IWDG) -> A>(&self, mut f: F) -> A {
81 self.iwdg.kr.write(|w| unsafe { w.key().bits(KR_ACCESS) });
83 let a = f(&self.iwdg);
84
85 self.iwdg.kr.write(|w| unsafe { w.key().bits(KR_RELOAD) });
87 a
88 }
89}
90
91impl WatchdogEnable for IndependentWatchdog {
92 type Time = MilliSeconds;
93
94 fn start<T: Into<Self::Time>>(&mut self, period: T) {
95 self.setup(period.into().0);
96
97 self.iwdg.kr.write(|w| unsafe { w.key().bits(KR_START) });
98 }
99}
100
101impl Watchdog for IndependentWatchdog {
102 fn feed(&mut self) {
103 self.iwdg.kr.write(|w| unsafe { w.key().bits(KR_RELOAD) });
104 }
105}
106