Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

hal: Countdown #26

Merged
merged 2 commits into from
Apr 1, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,11 @@ libc = "0.2.50"
lazy_static = "1.3.0"
nb = { version = "0.1.1", optional = true }
embedded-hal = { version = "0.2.2", optional = true }
bitrate = "0.1.1"

[dependencies.void]
default-features = false
version = "1.0.2"

[dev-dependencies]
simple-signal = "1.1.1"
Expand Down
76 changes: 75 additions & 1 deletion src/hal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,12 @@
//! flag is enabled.

use std::thread;
use std::time::Duration;
use std::time::{Duration, Instant};

use bitrate::Hertz;
use embedded_hal::blocking::delay::{DelayMs, DelayUs};
use embedded_hal::timer::CountDown;
use void::Void;

/// Implements the `embedded-hal` `DelayMs` and `DelayUs` traits.
#[derive(Debug, Default)]
Expand Down Expand Up @@ -89,3 +92,74 @@ impl DelayUs<u64> for Delay {
thread::sleep(Duration::from_micros(us));
}
}

/// Implements the `embedded-hal` `CountDown` trait.
#[derive(Debug, Copy, Clone)]
pub struct Timer {
now: Instant,
duration: Duration,
}

impl Timer {
/// Constructs a new `Timer`.
pub fn new() -> Self {
Self {
now: Instant::now(),
duration: Duration::from_micros(0),
}
}
}

pub struct Millisecond(pub u64);
pub struct MicroSecond(pub u64);
pub struct Second(pub u64);

impl From<Hertz<u64>> for MicroSecond {
fn from(item: Hertz<u64>) -> Self {
MicroSecond(item.0 * 1_000_000)
}
}

impl From<Millisecond> for MicroSecond {
fn from(item: Millisecond) -> Self {
MicroSecond(item.0 * 1_000)
}
}

impl From<Second> for MicroSecond {
fn from(item: Second) -> Self {
MicroSecond(item.0 * 1_000_000)
}
}

impl MicroSecond {
fn as_u64(&self) -> u64 {
let &MicroSecond(t) = self;
t
}
}

impl CountDown for Timer {
type Time = MicroSecond;

/// Start the timer with a `timeout`
fn start<T>(&mut self, timeout: T)
where
T: Into<MicroSecond>,
{
self.duration = Duration::from_micros(timeout.into().as_u64());
self.now = Instant::now();
}

/// Return `Ok` if the timer has wrapped
/// Automatically clears the flag and restarts the time
fn wait(&mut self) -> nb::Result<(), Void> {
if self.now.elapsed() >= self.duration {
let duration = Duration::from_micros(1);
thread::sleep(duration);
Ok(())
} else {
Err(nb::Error::WouldBlock)
}
}
}