FluenTech / embedded-time

Time(ing) library (Instant/Duration/Clock/Timer/Period/Frequency) for bare-metal embedded systems
Apache License 2.0
87 stars 17 forks source link

How to get the number of elapsed milliseconds as integer from a clock? #124

Closed sourcebox closed 2 years ago

sourcebox commented 2 years ago

I want to get the number of elapsed milliseconds within a driver. The following code does not compile:

struct Driver<Clock> {
    clock: Clock,
}

impl<Clock> Driver<Clock>
where
    Clock: embedded_time::Clock,
{
    fn new(clock: Clock) -> Self {
        Self { clock }
    }

    fn run(&self) {
        let millis: embedded_time::duration::Milliseconds<u32> = self
            .clock
            .try_now()
            .unwrap()
            .duration_since_epoch()
            .try_into()
            .unwrap();
    }
}

It throws the following error:

.try_into()
   |              ^^^^^^^^ the trait `TryFrom<embedded_time::duration::Generic<<Clock as embedded_time::Clock>::T>>` is not implemented for `Milliseconds`

The driver should (of course) not make any assumptions of the clock implementation. Is passing the clock as generic parameter the right way to do this?

sourcebox commented 2 years ago

I was able to solve it with some help from dirbaio@matrix.org. The where clause needs to be extended with u32: TryFrom<Clock::T>