ev3_drivebase/drivebase/
brake_mode.rs

1use super::DriveBase;
2use ev3dev_lang_rust::{Ev3Error, motors::TachoMotor};
3
4impl DriveBase {
5    /// Sets the brake mode of both motors. Its either `Coast`, `Brake` or `Hold`.
6    ///
7    /// # Errors
8    ///
9    /// Errors if it can't set the command
10    pub fn set_brake_mode(&self, brake_mode: BrakeMode) -> Result<&Self, Ev3Error> {
11        self.left.set_stop_action(brake_mode.as_ref())?;
12        self.right.set_stop_action(brake_mode.as_ref())?;
13        Ok(self)
14    }
15
16    /// Gets the brake mode for both motors. If the motors have different brake modes, this sets the right motor's
17    /// brake mode to match the left motor's.
18    ///
19    /// # Errors
20    ///
21    /// Errors if it can't read the brake mode
22    pub fn get_brake_mode(&self) -> Result<BrakeMode, Ev3Error> {
23        let left_brake_mode: BrakeMode = self.left.get_stop_action()?.into();
24        let right_brake_mode: BrakeMode = self.right.get_stop_action()?.into();
25
26        if right_brake_mode != left_brake_mode {
27            self.right.set_stop_action(left_brake_mode.as_ref())?;
28        }
29
30        Ok(left_brake_mode)
31    }
32}
33
34/// The brake mode of the motor
35#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
36pub enum BrakeMode {
37    /// The motor will freely coast to a stop. No active braking is applied.
38    Coast,
39    /// The motor will actively brake, resisting motion until it comes to a stop.
40    /// Slows the motor faster than `Coast` but does not hold position.
41    Brake,
42    /// The motor will actively hold its current position once stopped.
43    /// Useful for precise positioning, but can consume more power.
44    Hold,
45}
46
47impl AsRef<str> for BrakeMode {
48    fn as_ref(&self) -> &str {
49        match self {
50            Self::Coast => TachoMotor::STOP_ACTION_COAST,
51            Self::Brake => TachoMotor::STOP_ACTION_BRAKE,
52            Self::Hold => TachoMotor::STOP_ACTION_HOLD,
53        }
54    }
55}
56
57impl From<&str> for BrakeMode {
58    fn from(value: &str) -> Self {
59        match value {
60            TachoMotor::STOP_ACTION_BRAKE => Self::Brake,
61            TachoMotor::STOP_ACTION_HOLD => Self::Hold,
62            _ => Self::Coast,
63        }
64    }
65}
66
67impl From<String> for BrakeMode {
68    fn from(value: String) -> Self {
69        Self::from(value.as_str())
70    }
71}