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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
use core::ops::Deref;
use crate::target::{timer0, Interrupt, NVIC, TIMER0, TIMER1, TIMER2};
use embedded_hal::{prelude::*, timer};
use nb::{self, block};
use void::{unreachable, Void};
#[cfg(any(feature = "52832", feature = "52840"))]
use crate::target::{TIMER3, TIMER4};
pub trait TimerExt: Deref<Target = timer0::RegisterBlock> + Sized {
const INTERRUPT: Interrupt;
fn constrain(self) -> Timer<Self>;
}
macro_rules! impl_timer_ext {
($($timer:tt,)*) => {
$(
impl TimerExt for $timer {
const INTERRUPT: Interrupt = Interrupt::$timer;
fn constrain(self) -> Timer<Self> {
Timer::new(self)
}
}
)*
}
}
impl_timer_ext!(TIMER0, TIMER1, TIMER2,);
#[cfg(any(feature = "52832", feature = "52840"))]
impl_timer_ext!(TIMER3, TIMER4,);
pub struct Timer<T>(T);
impl<T> Timer<T>
where
T: TimerExt,
{
fn new(timer: T) -> Self {
timer
.shorts
.write(|w| w.compare0_clear().enabled().compare0_stop().enabled());
timer.prescaler.write(
|w| unsafe { w.prescaler().bits(4) },
);
timer.bitmode.write(|w| w.bitmode()._32bit());
Timer(timer)
}
pub fn free(self) -> T {
self.0
}
pub fn enable_interrupt(&mut self, nvic: &mut NVIC) {
self.0.intenset.modify(|_, w| w.compare0().set());
nvic.enable(T::INTERRUPT);
}
pub fn disable_interrupt(&mut self, nvic: &mut NVIC) {
self.0.intenclr.modify(|_, w| w.compare0().clear());
nvic.disable(T::INTERRUPT);
}
pub fn delay(&mut self, cycles: u32) {
self.start(cycles);
match block!(self.wait()) {
Ok(_) => {}
Err(x) => unreachable(x),
}
}
}
impl<T> timer::CountDown for Timer<T>
where
T: TimerExt,
{
type Time = u32;
fn start<Time>(&mut self, cycles: Time)
where
Time: Into<Self::Time>,
{
self.0.cc[0].write(|w|
unsafe { w.cc().bits(cycles.into()) });
self.0.tasks_clear.write(|w| unsafe { w.bits(1) });
self.0.tasks_start.write(|w| unsafe { w.bits(1) });
}
fn wait(&mut self) -> nb::Result<(), Void> {
if self.0.events_compare[0].read().bits() == 0 {
return Err(nb::Error::WouldBlock);
}
self.0.events_compare[0].write(|w| w);
Ok(())
}
}
impl<T> timer::Cancel for Timer<T>
where
T: TimerExt,
{
type Error = ();
fn cancel(&mut self) -> Result<(), Self::Error> {
self.0.tasks_stop.write(|w| unsafe { w.bits(1) });
self.0.events_compare[0].write(|w| w);
Ok(())
}
}