Crate hcsr04_async

Source
Expand description

§hc-sr04-async

This crate provides an asynchronous driver for the HC-SR04 ultrasonic distance sensor.

The driver is designed to work with Celsius and Fahrenheit temperatures and centimeters and inches for distance measurements.

§Features

  • blocking_trigger: (Default) This feature enables blocking behavior for the trigger pulse, ensuring more accurate timing. For 10us async is not very accurate, because it introduces a few microseconds of management. This should normally not affect the sensor, many do in fact still trigger if the actual trigger pulse was i.e. 15us. So if you absolutely need the core to do other things while waiting for the trigger pulse, you can disable this feature.

§Example

#![no_std]
#![no_main]

use defmt::*;
use embassy_executor::Spawner;
use embassy_rp::gpio::{Input, Level, Output, Pull};
use embassy_time::{Delay, Duration, Instant, Timer};
use hcsr04_async::{Config, DistanceUnit, Hcsr04, Now, TemperatureUnit};
use {defmt_rtt as _, panic_probe as _};

#[embassy_executor::main]
async fn main(_spawner: Spawner) {
    let p = embassy_rp::init(Default::default());
    info!("Running!");

    let trigger = Output::new(p.PIN_13, Level::Low);
    let echo = Input::new(p.PIN_28, Pull::None);

    let config = Config {
        distance_unit: DistanceUnit::Centimeters,
        temperature_unit: TemperatureUnit::Celsius,
    };

    // Create clock function that returns microseconds
    struct EmbassyClock;

    impl Now for EmbassyClock {
        fn now_micros(&self) -> u64 {
            Instant::now().as_micros()
        }
    }

    let clock = EmbassyClock;
    let delay = Delay;

    let mut sensor = Hcsr04::new(trigger, echo, config, clock, delay);

    // The temperature of the environment, if known, can be used to adjust the speed of sound.
    // If unknown, an average estimate must be used.
    let temperature = 24.0;

    loop {
        let distance = sensor.measure(temperature).await;
        match distance {
            Ok(distance) => {
                info!("Distance: {} cm", distance);
            }
            Err(e) => {
                info!("Error: {:?}", e);
            }
        }
        Timer::after(Duration::from_secs(1)).await;
    }
}

Structs§

Config
The configuration for the sensor.
Hcsr04
The HC-SR04 ultrasonic distance sensor driver.

Enums§

DistanceUnit
The distance unit to use for measurements.
TemperatureUnit
The temperature unit to use for measurements.

Traits§

Now