From a2d0c31d73c7d1667ae27dfc3b8c4da93b931b70 Mon Sep 17 00:00:00 2001 From: Sh3Rm4n Date: Tue, 22 Jun 2021 08:38:43 +0200 Subject: [PATCH] Readd MonoTimer This was accidentally removed in #192 --- CHANGELOG.md | 5 ++++- src/timer.rs | 49 ++++++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 52 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a25ee9d60..556beb28d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,7 +7,9 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ## Unreleased -No changes. +### Added + +- Readd MonoTimer. This was accidentally removed before. [#247] ## [v0.7.0] - 2021-06-18 @@ -333,6 +335,7 @@ let clocks = rcc [defmt]: https://github.com/knurling-rs/defmt [filter]: https://defmt.ferrous-systems.com/filtering.html +[#247]: https://github.com/stm32-rs/stm32f3xx-hal/pull/247 [#238]: https://github.com/stm32-rs/stm32f3xx-hal/pull/238 [#234]: https://github.com/stm32-rs/stm32f3xx-hal/pull/234 [#232]: https://github.com/stm32-rs/stm32f3xx-hal/pull/232 diff --git a/src/timer.rs b/src/timer.rs index 30bbaafbc..d5c7be67e 100644 --- a/src/timer.rs +++ b/src/timer.rs @@ -8,6 +8,9 @@ use core::convert::{From, TryFrom}; +use cortex_m::peripheral::DWT; +use void::Void; + use crate::hal::timer::{CountDown, Periodic}; #[cfg(any( feature = "stm32f301", @@ -58,7 +61,51 @@ use crate::pac::{TIM15, TIM16, TIM17, TIM2, TIM6}; use crate::pac::{TIM3, TIM7}; use crate::rcc::{Clocks, APB1, APB2}; use crate::time::rate::*; -use void::Void; + +/// A monotonic nondecreasing timer. +#[derive(Clone, Copy)] +pub struct MonoTimer { + frequency: Hertz, +} + +impl MonoTimer { + /// Creates a new `Monotonic` timer + pub fn new(mut dwt: DWT, clocks: Clocks) -> Self { + dwt.enable_cycle_counter(); + + // now the CYCCNT counter can't be stopped or resetted + drop(dwt); + + MonoTimer { + frequency: clocks.hclk(), + } + } + + /// Returns the frequency at which the monotonic timer is operating at + pub fn frequency(self) -> Hertz { + self.frequency + } + + /// Returns an `Instant` corresponding to "now" + pub fn now(self) -> Instant { + Instant { + now: DWT::get_cycle_count(), + } + } +} + +/// A measurement of a monotonically nondecreasing clock +#[derive(Clone, Copy)] +pub struct Instant { + now: u32, +} + +impl Instant { + /// Ticks elapsed since the `Instant` was created + pub fn elapsed(self) -> u32 { + DWT::get_cycle_count().wrapping_sub(self.now) + } +} /// Associated clocks with timers pub trait PclkSrc {