1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
use crate::{
pac::{DBG, FWDGT},
time::MilliSeconds,
};
use embedded_hal::watchdog::{Watchdog, WatchdogEnable};
pub struct FreeWatchdog {
fwdgt: FWDGT,
}
const LSI_KHZ: u32 = 40;
const MAX_PRESCALER: u8 = 8;
const MAX_RELOAD: u16 = 0xFFF;
impl FreeWatchdog {
pub fn new(fwdgt: FWDGT) -> Self {
FreeWatchdog { fwdgt }
}
pub fn stop_on_debug(&self, dbg: &DBG, stop: bool) {
dbg.ctl0.modify(|_, w| w.fwdgt_hold().bit(stop));
}
fn setup(&self, timeout_ms: u32) {
let mut prescaler = 0;
while prescaler < MAX_PRESCALER && Self::timeout_period(prescaler, MAX_RELOAD) < timeout_ms
{
prescaler += 1;
}
let max_period = Self::timeout_period(prescaler, MAX_RELOAD);
let max_reload = u32::from(MAX_RELOAD);
let reload = (timeout_ms * max_reload / max_period).min(max_reload) as u16;
self.access_registers(|fwdgt| {
fwdgt.psc.modify(|_, w| w.psc().bits(prescaler));
fwdgt.rld.modify(|_, w| w.rld().bits(reload));
});
}
fn is_prescaler_updating(&self) -> bool {
self.fwdgt.stat.read().pud().is_ongoing()
}
pub fn interval(&self) -> MilliSeconds {
while self.is_prescaler_updating() {}
let prescaler = self.fwdgt.psc.read().psc().bits();
let reload = self.fwdgt.rld.read().rld().bits();
let ms = Self::timeout_period(prescaler, reload);
MilliSeconds(ms)
}
fn timeout_period(prescaler: u8, reload: u16) -> u32 {
let divider: u32 = match prescaler {
0b000 => 4,
0b001 => 8,
0b010 => 16,
0b011 => 32,
0b100 => 64,
0b101 => 128,
0b110 => 256,
0b111 => 256,
_ => panic!("Invalid FWDGT prescaler divider"),
};
(u32::from(reload) + 1) * divider / LSI_KHZ
}
fn access_registers<A, F: FnMut(&FWDGT) -> A>(&self, mut f: F) -> A {
self.fwdgt.ctl.write(|w| w.cmd().enable());
let a = f(&self.fwdgt);
self.fwdgt.ctl.write(|w| w.cmd().reset());
a
}
}
impl WatchdogEnable for FreeWatchdog {
type Time = MilliSeconds;
fn start<T: Into<Self::Time>>(&mut self, period: T) {
self.setup(period.into().0);
self.fwdgt.ctl.write(|w| w.cmd().start());
}
}
impl Watchdog for FreeWatchdog {
fn feed(&mut self) {
self.fwdgt.ctl.write(|w| w.cmd().reset());
}
}