Skip to content

DelayUs should not be implemented with thread::sleep #6

@tafia

Description

@tafia

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 { }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions