thermostat/src/timer.rs

48 lines
1.1 KiB
Rust
Raw Normal View History

2019-03-15 01:13:25 +08:00
use core::cell::RefCell;
use core::ops::Deref;
2019-03-15 01:13:25 +08:00
use cortex_m::interrupt::Mutex;
use cortex_m_rt::exception;
use stm32f4xx_hal::{
rcc::Clocks,
time::U32Ext,
2019-03-15 01:13:25 +08:00
timer::{Timer, Event as TimerEvent},
stm32::SYST,
};
2019-03-19 04:41:51 +08:00
/// Rate in Hz
const TIMER_RATE: u32 = 500;
2019-03-19 04:41:51 +08:00
/// Interval duration in milliseconds
2019-03-15 01:13:25 +08:00
const TIMER_DELTA: u32 = 1000 / TIMER_RATE;
/// Elapsed time in milliseconds
static TIMER_MS: Mutex<RefCell<u32>> = Mutex::new(RefCell::new(0));
2019-03-19 04:41:51 +08:00
/// Setup SysTick exception
2019-03-15 01:13:25 +08:00
pub fn setup(syst: SYST, clocks: Clocks) {
let mut timer = Timer::syst(syst, TIMER_RATE.hz(), clocks);
timer.listen(TimerEvent::TimeOut);
}
2019-03-19 04:41:51 +08:00
/// SysTick exception (Timer)
2019-03-15 01:13:25 +08:00
#[exception]
fn SysTick() {
cortex_m::interrupt::free(|cs| {
*TIMER_MS.borrow(cs)
.borrow_mut() += TIMER_DELTA;
});
}
2019-03-19 04:41:51 +08:00
/// Obtain current time in milliseconds
pub fn now() -> u32 {
cortex_m::interrupt::free(|cs| {
2019-03-15 01:13:25 +08:00
*TIMER_MS.borrow(cs)
.borrow()
.deref()
})
2019-03-15 01:13:25 +08:00
}
2020-05-29 02:45:42 +08:00
/// block for at least `amount` milliseconds
2020-06-01 01:54:18 +08:00
pub fn sleep(amount: u32) {
2020-05-29 02:45:42 +08:00
let start = now();
while now() - start <= amount {}
}