rust-embedded / embedded-hal

A Hardware Abstraction Layer (HAL) for embedded systems
Apache License 2.0
1.88k stars 188 forks source link

Need for a Generic Instant/Time/Duration #122

Open tib888 opened 5 years ago

tib888 commented 5 years ago

Hi All,

I'v run into the need for a generic "Instant" implementation several times.

Depending on your application you can decide what resolution ticks you need (and how often you can tolerate an overflow) and what kind of HW resources you have to increase a counter.

Then this implementation of "Instant" trait(s) could be passed to various stuff, like:

Each of these implementations would be generic about the "Instant" trait(s), but all of them likely

The std time, duration is too big overhead for an embedded system, with this abstraction each application could be provided with a well optimized time measurement utility.

Please comment!

Michael-F-Bryan commented 5 years ago

The std time, duration is too big overhead for an embedded system

I'm curious what you mean by core::time::Duration having too much of an overhead?

Its definition is struct Duration { secs: u64, nanos: u32 }, so memory-wise there isn't a problem. Likewise, operations like addition are pretty trivial and would optimise down to nothing.

In my application, I'm using the time since a stable reference point (e.g. power on or the unix epoch) for time-keeping purposes.

/// Something which records the elapsed real time.
///
/// This uses shared references because it may be shared between multiple
/// components at any one time.
pub trait SystemClock {
    /// The amount of time that has passed since a clock-specific reference
    /// point (e.g. device startup or the unix epoch).
    fn elapsed(&self) -> Duration;
}
JOE1994 commented 4 years ago

In my application, I'm using the time since a stable reference point (e.g. power on or the unix epoch) for time-keeping purposes.

First of all, thanks for sharing your application repo! In clock.rs of your application, it seems that measuring the actual elapsed time is possible only when std is enabled for std::time::Instant support.

May I ask how I could implement such 'time-measuring' functionality without std support?? Thank you 😄

Michael-F-Bryan commented 4 years ago

On an embedded device (most #[no_std] applicationd) you often bring your own clock.

This is typically implemented by registering a SysTick interrupt handler and incrementing a counter every time it's triggered. From there you can do some math with the clock frequency to turn ticks into seconds. I don't want to make assumptions about your application or force people to use whatever I implement, so we use a trait.

If you're compiling with the full standard library we know we'll always have access to the "current time" via the OS, so I've provided an implementation instead of forcing every user to write it themselves.