Crates.io | hcsr04 |
lib.rs | hcsr04 |
version | 0.1.3 |
created_at | 2025-08-19 13:20:31.60559+00 |
updated_at | 2025-08-20 05:49:28.768841+00 |
description | A platform-agnostic, `no_std` driver for the HC-SR04 ultrasonic distance sensor |
homepage | |
repository | https://github.com/aittkx/embedded-drivers |
max_upload_size | |
id | 1801876 |
size | 54,399 |
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:
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"] }
defmt
: Use defmt
logging to print messages.Usage examples can be found in the examples folder and run on the esp32-c3
board.
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 provides a simulation solution for embedded and IoT system engineers.
F1
OR ⌘ + ⇧ + P
to open the command palette.Wokwi: Start Simulator and Wait for Debugger
and press enter.Debug
button to start debugging.Licensed under either of: