rust-embedded/linux-embedded-hal

DelayUs should not be implemented with thread::sleep

tafia opened this issue · 0 comments

tafia commented

I believe thread::sleep cannot provide microsecond precision on linux.

Failing example:

extern crate embedded_hal;
extern crate linux_embedded_hal as hal;

use embedded_hal::blocking::delay::DelayUs;

fn main() {
    let us = 10u8;
    let t = ::std::time::SystemTime::now();
    let mut delay = hal::Delay{};
    delay.delay_us(us);
    println!("Expecting {}us, got {}us", us, t.elapsed().unwrap().subsec_nanos() / 1000);
}

Prints

Running `target/release/test_hal`
Expecting 10us, got 84us

What is the recommended way to get this level of precision?

As an example this very bad loop works:

pub fn delay_us(us: u32) {
    let target = Instant::now() + Duration::new(0, us * 1000);
    while Instant::now() < target { }
}