-
Notifications
You must be signed in to change notification settings - Fork 267
/
Copy pathtime_driver_timg.rs
98 lines (80 loc) · 3 KB
/
time_driver_timg.rs
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
use core::cell::RefCell;
use critical_section::{CriticalSection, Mutex};
use pac::TIMG0;
use super::AlarmState;
use crate::{
clock::Clocks,
pac,
prelude::*,
timer::{Timer, Timer0},
};
pub const ALARM_COUNT: usize = 1;
pub type TimerType = Timer<Timer0<TIMG0>>;
pub struct EmbassyTimer {
pub(crate) alarms: Mutex<[AlarmState; ALARM_COUNT]>,
pub(crate) timer: Mutex<RefCell<Option<TimerType>>>,
}
const ALARM_STATE_NONE: AlarmState = AlarmState::new();
embassy_time::time_driver_impl!(static DRIVER: EmbassyTimer = EmbassyTimer {
alarms: Mutex::new([ALARM_STATE_NONE; ALARM_COUNT]),
timer: Mutex::new(RefCell::new(None)),
});
impl EmbassyTimer {
pub(crate) fn now() -> u64 {
critical_section::with(|cs| DRIVER.timer.borrow_ref(cs).as_ref().unwrap().now())
}
pub(crate) fn trigger_alarm(&self, n: usize, cs: CriticalSection) {
let alarm = &self.alarms.borrow(cs)[n];
// safety:
// - we can ignore the possiblity of `f` being unset (null) because of the
// safety contract of `allocate_alarm`.
// - other than that we only store valid function pointers into alarm.callback
let f: fn(*mut ()) = unsafe { core::mem::transmute(alarm.callback.get()) };
f(alarm.ctx.get());
}
fn on_interrupt(&self, id: u8) {
critical_section::with(|cs| {
let mut tg = self.timer.borrow_ref_mut(cs);
let tg = tg.as_mut().unwrap();
tg.clear_interrupt();
self.trigger_alarm(id as usize, cs);
});
}
pub fn init(clocks: &Clocks, mut timer: TimerType) {
use crate::{interrupt, interrupt::Priority};
// set divider to get a 1mhz clock. abp (80mhz) / 80 = 1mhz... // TODO assert
// abp clock is the source and its at the correct speed for the divider
timer.set_divider(clocks.apb_clock.to_MHz() as u16);
critical_section::with(|cs| DRIVER.timer.borrow_ref_mut(cs).replace(timer));
interrupt::enable(pac::Interrupt::TG0_T0_LEVEL, Priority::max()).unwrap();
#[interrupt]
fn TG0_T0_LEVEL() {
DRIVER.on_interrupt(0);
}
}
pub(crate) fn set_alarm(
&self,
alarm: embassy_time::driver::AlarmHandle,
timestamp: u64,
) -> bool {
critical_section::with(|cs| {
let now = Self::now();
let alarm_state = unsafe { self.alarms.borrow(cs).get_unchecked(alarm.id() as usize) };
let mut tg = self.timer.borrow_ref_mut(cs);
let tg = tg.as_mut().unwrap();
if timestamp < now {
tg.unlisten();
alarm_state.timestamp.set(u64::MAX);
return false;
}
alarm_state.timestamp.set(timestamp);
tg.load_alarm_value(timestamp);
tg.listen();
tg.set_counter_decrementing(false);
tg.set_auto_reload(false);
tg.set_counter_active(true);
tg.set_alarm_active(true);
true
})
}
}