hcsr04

Crates.iohcsr04
lib.rshcsr04
version0.1.3
created_at2025-08-19 13:20:31.60559+00
updated_at2025-08-20 05:49:28.768841+00
descriptionA platform-agnostic, `no_std` driver for the HC-SR04 ultrasonic distance sensor
homepage
repositoryhttps://github.com/aittkx/embedded-drivers
max_upload_size
id1801876
size54,399
aittkx (aittkx)

documentation

https://docs.rs/hcsr04

README

hcsr04

A platform-agnostic, no_std driver for the HC-SR04 ultrasonic distance sensor using embedded-hal and embedded-hal-async traits.

This driver allows you to:

  • Measure distance using the HC-SR04 sensor.
  • Compensate for temperature effects on distance measurement.

Installation

Add hcsr04 to your project:

cargo add hcsr04 --features defmt

OR add the following to your Cargo.toml:

[dependencies]
hcsr04 = { version = "0.1", features = ["defmt"] }

Optional Cargo features

  • defmt: Use defmt logging to print messages.

Examples

Usage examples can be found in the examples folder and run on the esp32-c3 board.

Measure distance

Full code see ultrasonic_led.rs

#[embassy_executor::task]
/// Task to measure distance and control LED based on the distance.
///
/// # Arguments
///
/// * `trig` - The trigger pin of the HC-SR04 sensor.
/// * `echo` - The echo pin of the HC-SR04 sensor.
/// * `led` - The LED pin to control based on the distance.
async fn ultrasonic_led(trig: AnyPin<'static>, echo: AnyPin<'static>, led: AnyPin<'static>) {
    info!("Starting ultrasonic led task");
    // Init GPIO
    let mut led = Output::new(led, Level::Low, OutputConfig::default());
    let trig = Output::new(trig, Level::Low, OutputConfig::default());
    let echo = Input::new(echo, InputConfig::default().with_pull(Pull::Down));
    // Create a HC-SR04 sensor instance
    let mut hcsr04 = Hcsr04::builder()
        .trig(trig)
        .echo(echo)
        .delay(Delay)
        .temperature(NoTemperatureCompensation)
        .build();
    loop {
        // Measure distance
        let distance = match hcsr04.measure_distance().await {
            Ok(distance) => distance,
            Err(e) => {
                error!("Fail to measure {}", e);
                continue;
            }
        };
        info!("measure distance value is {} cm.", distance);
        if distance < 30.0 {
            led.set_high();
        } else {
            led.set_low();
        }
        Timer::after_millis(500).await;
    }
}

Wokwi

Wokwi provides a simulation solution for embedded and IoT system engineers.

  • Install the Wokwi for VS Code extension.
  • Press F1 OR ⌘ + ⇧ + P to open the command palette.
  • Type in Wokwi: Start Simulator and Wait for Debugger and press enter.
  • In the Wokwi simulator, click on the Debug button to start debugging.

License

Licensed under either of:

Commit count: 5

cargo fmt