ev3dev_rs/pupdevices/touch_sensor.rs
1use crate::{
2 attribute::AttributeName::*,
3 error::{Ev3Error, Ev3Result},
4 parameters::SensorPort,
5 sensor_driver::{SensorDriver, SensorType},
6};
7
8/// A stock EV3 touch sensor.
9///
10/// # Examples
11/// ``` no_run
12/// use ev3dev_rs::pupdevices::TouchSensor;
13/// use ev3dev_rs::parameters::SensorPort;
14///
15/// let touch_sensor = TouchSensor::new(SensorPort::In1)?;
16///
17/// println!("Is the sensor pressed? : {}", if touch_sensor.pressed()? {"Yes"} else {"No"});
18///
19/// ```
20pub struct TouchSensor {
21 driver: SensorDriver,
22}
23
24impl TouchSensor {
25 /// Find a `TouchSensor` on the given port.
26 ///
27 /// Will return `SensorNotFound` if no sensor is found
28 /// or `IncorrectSensorType` if the found sensor is not a `TouchSensor`.
29 pub fn new(port: SensorPort) -> Ev3Result<Self> {
30 let driver = SensorDriver::new(SensorType::Touch, port)?;
31 Ok(Self { driver })
32 }
33
34 /// Returns `true` if the sensor is currently pressed and `false` otherwise.
35 pub fn pressed(&self) -> Ev3Result<bool> {
36 // only one possible mode, no need to check
37 let raw_value = self.driver.read_attribute(Value0)?;
38
39 let int_value: u8 = raw_value.parse()?;
40
41 match int_value {
42 0 => Ok(false),
43 1 => Ok(true),
44 _ => Err(Ev3Error::InvalidValue {
45 func: "TouchSensor::pressed".into(),
46 value: raw_value,
47 }),
48 }
49 }
50}