hc-sr04

Crates.iohc-sr04
lib.rshc-sr04
version0.1.2
sourcesrc
created_at2022-09-23 21:31:14.365142
updated_at2024-05-02 16:54:31.472287
descriptionRaspberry Pi Rust driver for the HC-SR04 ultrasonic distance sensor.
homepage
repositoryhttps://github.com/marcoradocchia/hc-sr04
max_upload_size
id672696
size51,764
Marco Radocchia (marcoradocchia)

documentation

README

HC-SR04

GitHub source size GitHub open issues GitHub open pull requests GitHub sponsors Crates.io downloads Crates.io version GitHub license

This crate provides a driver for the HC-SR04/HC-SR04P ultrasonic distance sensor on Raspberry Pi, using rppal to access Raspberry Pi's GPIO.

Examples

Usage examples can be found in the examples folder.

Measure distance

use hc_sr04::{HcSr04, Unit};

// Initialize driver.
let mut ultrasonic = HcSr04::new(
    24,          // TRIGGER -> Gpio pin 24
    23,          // ECHO -> Gpio pin 23
    Some(23_f32) // Ambient temperature (if `None` defaults to 20.0C)
).unwrap();

// Perform distance measurement, specifying measuring unit of return value.
match ultrasonic.measure_distance(Unit::Meters).unwrap() {
    Some(dist) => println!("Distance: {.2}m", dist),
    None => println!("Object out of range"),
}

Calibrate measurement

Distance measurement can be calibrated at runtime using the HcSr04::calibrate method that this library exposes, passing the current ambient temperature as f32.

use hc_sr04::{HcSr04, Unit};

// Initialize driver.
let mut ultrasonic = HcSr04::new(24, 23, None).unwrap();

// Calibrate measurement with ambient temperature.
ultrasonic.calibrate(23_f32);

// Perform distance measurement.
match ultrasonic.measure_distance(Unit::Centimeters).unwrap() {
    Some(dist) => println!("Distance: {.1}cm", dist),
    None => println!("Object out of range"),
}
Commit count: 16

cargo fmt