ev3dev_rs/pupdevices/ultrasonic_sensor.rs
1use crate::{
2 attribute::AttributeName,
3 error::Ev3Result,
4 parameters::SensorPort,
5 sensor_driver::{SensorDriver, SensorMode, SensorType},
6};
7
8/// A stock EV3 ultrasonic sensor.
9///
10/// # Examples
11/// ``` no_run
12/// use ev3dev_rs::pupdevices::UltrasonicSensor;
13/// use ev3dev_rs::parameters::SensorPort;
14///
15/// let ultrasonic_sensor = UltrasonicSensor::new(SensorPort::In1)?;
16///
17/// println!("Distance (in): {}", ultrasonic_sensor.distance_in()?);
18/// println!("Distance (cm): {}", ultrasonic_sensor.distance_cm()?);
19///
20/// ```
21pub struct UltrasonicSensor {
22 driver: SensorDriver,
23}
24
25impl UltrasonicSensor {
26 /// Find an `UltrasonicSensor` on the given port.
27 ///
28 /// Will return `SensorNotFound` if no sensor is found
29 /// or `IncorrectSensorType` if the found sensor is not an `UltrasonicSensor`.
30 pub fn new(port: SensorPort) -> Ev3Result<Self> {
31 let driver = SensorDriver::new(SensorType::Ultrasonic, port)?;
32 Ok(Self { driver })
33 }
34
35 /// Get the distance value of the sensor in inches to one decimal place (0-2550).
36 pub fn distance_in(&self) -> Ev3Result<f32> {
37 if self.driver.mode.get() != SensorMode::UltrasonicDistanceIn {
38 self.driver.set_mode(SensorMode::UltrasonicDistanceIn)?;
39 }
40 Ok(self
41 .driver
42 .read_attribute(AttributeName::Value0)?
43 .parse::<f32>()?
44 / 10.0)
45 }
46
47 /// Get the distance value of the sensor in centimeters to one decimal place (0-1003).
48 pub fn distance_cm(&self) -> Ev3Result<f32> {
49 if self.driver.mode.get() != SensorMode::UltrasonicDistanceCm {
50 self.driver.set_mode(SensorMode::UltrasonicDistanceCm)?;
51 }
52 Ok(self
53 .driver
54 .read_attribute(AttributeName::Value0)?
55 .parse::<f32>()?
56 / 10.0)
57 }
58}