Struct hc_sr04::HcSr04

source ·
pub struct HcSr04 { /* private fields */ }
Expand description

HC-SR04 ultrasonic sensor on Raspberry Pi.

§Fileds

  • trig: TRIGGER output GPIO pin
  • echo: ECHO input GPIO pin
  • temp: ambient Temperature measure calibration
  • sound_speed: speed of sound given the ambient Temperature
  • timeout: ECHO pin polling timeout, considering the maximum measuring range of 4m for the sensor and the speed of sound given the ambient Temperature

Implementations§

source§

impl HcSr04

source

pub fn new(trig: u8, echo: u8, temp: Option<f32>) -> Result<Self>

Initialize HC-SR04 sensor and register GPIO interrupt on echo pin for RisingEdge events in order to poll it for bouncing UltraSonic waves detection.

§Parameters
  • trig: TRIGGER output GPIO pin
  • echo: ECHO input GPIO pin
  • temp: ambient TEMPERATURE used for calibration (if None defaults to 20.0)
Examples found in repository?
examples/distance.rs (line 6)
4
5
6
7
8
9
10
11
12
13
14
15
16
fn run() -> Result<()> {
    // TRIGGER on GPIO Pin 24 & ECHO on GPIO Pin 23.
    let mut ultrasonic = HcSr04::new(24, 23, None)?;

    loop {
        match ultrasonic.measure_distance(Unit::Meters)? {
            Some(dist) => println!("Distance: {:.2}m", dist),
            None => println!("Object out of range"),
        }

        thread::sleep(Duration::from_secs(1));
    }
}
More examples
Hide additional examples
examples/door.rs (line 15)
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
fn run() -> Result<()> {
    // TRIGGER on GPIO Pin 24 & ECHO on GPIO Pin 23.
    let mut ultrasonic = HcSr04::new(24, 23, None)?;

    let below_threshold = |ultrasonic: &mut HcSr04| -> Result<bool> {
        Ok(ultrasonic
            .measure_distance(Unit::Meters)?
            .unwrap_or(f32::MAX)
            < THRESHOLD_DIST)
    };

    let mut closed = true;
    loop {
        // If measured distance is lower than THRESHOLD_DIST, door is open.
        if below_threshold(&mut ultrasonic)? == closed {
            closed = !closed;
            match closed {
                true => println!("Door closed!"),
                false => println!("Door opened!"),
            }
        }

        thread::sleep(Duration::from_millis(500));
    }
}
source

pub fn calibrate(&mut self, temp: f32)

Calibrate the sensor with the given ambient temperature (temp) expressed as Celsius degrees.

source

pub fn measure_distance(&mut self, unit: Unit) -> Result<Option<f32>>

Perform distance measurement.

Returns Ok variant if measurement succedes. Inner Option value is None if no object is present within maximum measuring range (4m); otherwhise, on Some variant instead, contained value represents distance expressed as the specified unit (unit of measure).

Examples found in repository?
examples/distance.rs (line 9)
4
5
6
7
8
9
10
11
12
13
14
15
16
fn run() -> Result<()> {
    // TRIGGER on GPIO Pin 24 & ECHO on GPIO Pin 23.
    let mut ultrasonic = HcSr04::new(24, 23, None)?;

    loop {
        match ultrasonic.measure_distance(Unit::Meters)? {
            Some(dist) => println!("Distance: {:.2}m", dist),
            None => println!("Object out of range"),
        }

        thread::sleep(Duration::from_secs(1));
    }
}
More examples
Hide additional examples
examples/door.rs (line 19)
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
fn run() -> Result<()> {
    // TRIGGER on GPIO Pin 24 & ECHO on GPIO Pin 23.
    let mut ultrasonic = HcSr04::new(24, 23, None)?;

    let below_threshold = |ultrasonic: &mut HcSr04| -> Result<bool> {
        Ok(ultrasonic
            .measure_distance(Unit::Meters)?
            .unwrap_or(f32::MAX)
            < THRESHOLD_DIST)
    };

    let mut closed = true;
    loop {
        // If measured distance is lower than THRESHOLD_DIST, door is open.
        if below_threshold(&mut ultrasonic)? == closed {
            closed = !closed;
            match closed {
                true => println!("Door closed!"),
                false => println!("Door opened!"),
            }
        }

        thread::sleep(Duration::from_millis(500));
    }
}

Trait Implementations§

source§

impl Debug for HcSr04

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl Freeze for HcSr04

§

impl !RefUnwindSafe for HcSr04

§

impl Send for HcSr04

§

impl Sync for HcSr04

§

impl Unpin for HcSr04

§

impl !UnwindSafe for HcSr04

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.