Skip to main content

embassy_embedded_time/
lib.rs

1//! # Embassy `embedded-time`
2//!
3//! This library provides an [embedded_time::Clock] that can be used with [embassy].
4//!
5//! The provided [embedded_time::Clock] implementation is based on [embassy_time].
6//!
7//! # Usage
8//!
9//! ```rust
10//! use embassy_embedded_time::EmbassyClock;
11//! use embedded_time::Clock;
12//!
13//! let clock = EmbassyClock::default();
14//!
15//! let now = clock.try_now().unwrap();
16//! println!("Current time: {:?}", now);
17//!
18//! ```
19
20#![no_std]
21
22use embedded_time::clock::Error;
23use embedded_time::duration::Fraction;
24use embedded_time::{Clock, Instant};
25
26/// A clock with at maximum microsecond precision.
27/// The actual precision depends on the tick rate configured for the underlying `embassy_time` clock.
28///
29/// To construct a clock, use [EmbassyClock::default()].
30///
31/// The clock is "started" when it is constructed.
32///
33/// # Limitations
34/// The clock represents up to ~584542 years worth of time, after which it will roll over.
35#[derive(Copy, Clone, Debug)]
36pub struct EmbassyClock {
37    start: embassy_time::Instant,
38}
39
40impl Default for EmbassyClock {
41    fn default() -> Self {
42        EmbassyClock {
43            start: embassy_time::Instant::now(),
44        }
45    }
46}
47
48impl Clock for EmbassyClock {
49    /// With a 64-bit tick register, the clock can represent times up to approximately 584542 years in
50    /// duration, after which the clock will roll over.
51    type T = u64;
52
53    /// Each tick of the clock is equivalent to 1 microsecond.
54    const SCALING_FACTOR: Fraction = Fraction::new(1, 1_000_000);
55
56    /// Get the current time from the clock.
57    fn try_now(&self) -> Result<Instant<Self>, Error> {
58        let now = embassy_time::Instant::now();
59
60        let elapsed = now.duration_since(self.start);
61
62        Ok(Instant::new(elapsed.as_micros()))
63    }
64}