pounder_test/src/hardware/cycle_counter.rs

41 lines
930 B
Rust
Raw Normal View History

2021-02-17 19:08:03 +08:00
use rtic::cyccnt::{Duration, Instant, U32Ext};
use stm32h7xx_hal::time::Hertz;
pub struct CycleCounter {
2021-02-17 19:59:24 +08:00
next_tick: Option<Instant>,
2021-02-17 19:08:03 +08:00
ticks: u32,
increment: Duration,
}
impl CycleCounter {
pub fn new(
mut dwt: cortex_m::peripheral::DWT,
cpu_frequency: impl Into<Hertz>,
) -> Self {
dwt.enable_cycle_counter();
let increment =
((cpu_frequency.into().0 as f32 / 1000.0) as u32).cycles();
Self {
increment,
ticks: 0,
2021-02-17 19:59:24 +08:00
next_tick: None,
2021-02-17 19:08:03 +08:00
}
}
pub fn current_ms(&mut self) -> u32 {
2021-02-17 19:59:24 +08:00
if self.next_tick.is_none() {
self.next_tick = Some(Instant::now() + self.increment);
}
2021-02-17 19:08:03 +08:00
let now = Instant::now();
2021-02-17 19:59:24 +08:00
while now > self.next_tick.unwrap() {
*self.next_tick.as_mut().unwrap() += self.increment;
2021-02-17 19:08:03 +08:00
self.ticks += 1;
}
self.ticks
}
}