ev3dev_rs/robotics/
drive_base.rs

1use crate::pid::Pid;
2use crate::pupdevices::GyroSensor;
3use crate::robotics::GyroController;
4use crate::Ev3Error;
5use crate::{parameters::Stop, pupdevices::Motor, Ev3Result};
6use fixed::traits::{LossyInto, ToFixed};
7use fixed::types::I32F32;
8use scopeguard::defer;
9use std::cell::Cell;
10use std::time::Duration;
11use tokio::time::interval;
12
13/// A pybricks-like `DriveBase`.
14///
15/// Using gyroscope(s) is highly recommended in order to get the most accurate actions
16///
17/// # Examples
18///
19/// ``` no_run
20/// use ev3dev_rs::parameters::{Direction, MotorPort, SensorPort, Stop};
21/// use ev3dev_rs::pupdevices::{Motor, GyroSensor};
22/// use ev3dev_rs::robotics::DriveBase;
23///
24/// let left = Motor::new(MotorPort::OutA, Direction::CounterClockwise)?;
25/// let right = Motor::new(MotorPort::OutD, Direction::CounterClockwise)?;
26///
27/// // no gyro
28/// let drive = DriveBase::new(&left, &right, 62.4, 130.5)?;
29///
30/// // with gyro
31/// let gyro = GyroSensor::new(SensorPort::In1)?;
32///
33/// let drive = DriveBase::new(&left, &right, 62.4, 130.5)?.with_gyro(&gyro)?;
34///
35/// // you have to explicitly enable the gyro
36/// drive.use_gyro(true)?;
37///
38/// // default is 500
39/// drive.set_straight_speed(600)?;
40///
41/// // default should be coast
42/// // unlike pybricks, the stop action doesn't affect whether the robot tracks it's position and heading
43/// drive.set_stop_action(Stop::Hold)?;
44///
45/// drive.straight(500).await?;
46/// drive.turn(90).await?;
47/// ```
48pub struct DriveBase<'a> {
49    left_motor: &'a Motor,
50    right_motor: &'a Motor,
51    left_start_angle: i32,
52    right_start_angle: i32,
53    min_speed: I32F32,
54    wheel_diameter: I32F32,
55    axle_track: I32F32,
56    straight_speed: Cell<I32F32>,
57    turn_speed: Cell<I32F32>,
58    prev_encoder_heading: Cell<I32F32>,
59    distance_pid: Pid,
60    heading_pid: Pid,
61    distance_target: Cell<I32F32>,
62    heading_target: Cell<I32F32>,
63    distance_tolerance: Cell<I32F32>,
64    heading_tolerance: Cell<I32F32>,
65    using_gyros: Cell<bool>,
66    gyros: Option<GyroController<'a>>,
67}
68
69impl<'a> DriveBase<'a> {
70    /// Creates a new `DriveBase` with the defined parameters.
71    ///
72    /// Wheel diameter and axle track are in mm.
73    ///
74    /// Using a gyroscope is highly recommended, see `with_gyro` or `with_gyros`.
75    pub fn new<Number>(
76        left_motor: &'a Motor,
77        right_motor: &'a Motor,
78        wheel_diameter: Number,
79        axle_track: Number,
80    ) -> Ev3Result<Self>
81    where
82        Number: ToFixed,
83    {
84        left_motor.set_ramp_up_setpoint(2000)?;
85        right_motor.set_ramp_up_setpoint(2000)?;
86
87        left_motor.set_ramp_down_setpoint(1800)?;
88        right_motor.set_ramp_down_setpoint(1800)?;
89
90        Ok(Self {
91            left_motor,
92            right_motor,
93            left_start_angle: left_motor.angle()?,
94            right_start_angle: right_motor.angle()?,
95            min_speed: I32F32::from_num(100),
96            wheel_diameter: I32F32::from_num(wheel_diameter),
97            axle_track: I32F32::from_num(axle_track),
98            straight_speed: Cell::new(I32F32::from_num(500)),
99            turn_speed: Cell::new(I32F32::from_num(550)),
100            prev_encoder_heading: Cell::new(I32F32::ZERO),
101            distance_pid: Pid::new(10, 0, 8, 0, 0),
102            heading_pid: Pid::new(10, 0, 5, 0, 0),
103            distance_target: Cell::new(I32F32::ZERO),
104            heading_target: Cell::new(I32F32::ZERO),
105            distance_tolerance: Cell::new(I32F32::from_num(4)),
106            heading_tolerance: Cell::new(I32F32::from_num(0.75)),
107            using_gyros: Cell::new(false),
108            gyros: None,
109        })
110    }
111
112    /// Adds a single gyro sensor to the `DriveBase`.
113    ///
114    /// # Examples
115    ///
116    /// ``` no_run
117    /// use ev3dev_rs::parameters::{Direction, MotorPort, SensorPort, Stop};
118    ///
119    /// use ev3dev_rs::pupdevices::{Motor, GyroSensor};
120    ///
121    /// use ev3dev_rs::robotics::DriveBase;
122    ///
123    /// let left = Motor::new(MotorPort::OutA, Direction::CounterClockwise)?;
124    ///
125    /// let right = Motor::new(MotorPort::OutD, Direction::CounterClockwise)?;
126    ///
127    /// let gyro = GyroSensor::new(SensorPort::In1)?;
128    ///
129    /// let drive = DriveBase::new(&left, &right, 62.4, 130.5)?.with_gyro(&gyro)?;
130    ///
131    /// // you have to explicitly enable the gyro
132    ///
133    /// drive.use_gyro(true)?;
134    /// ```
135    pub fn with_gyro<'b>(mut self, gyro_sensor: &'b GyroSensor) -> Ev3Result<Self>
136    where
137        'b: 'a,
138    {
139        self.gyros = Some(GyroController::new(vec![gyro_sensor])?);
140        Ok(self)
141    }
142
143    /// Adds multiple gyro sensors to the `DriveBase`.
144    ///
145    /// # Examples
146    ///
147    /// ``` no_run
148    /// use ev3dev_rs::parameters::{Direction, MotorPort, SensorPort, Stop};
149    ///
150    /// use ev3dev_rs::pupdevices::{Motor, GyroSensor};
151    ///
152    /// use ev3dev_rs::robotics::DriveBase;
153    ///
154    /// let left = Motor::new(MotorPort::OutA, Direction::CounterClockwise)?;
155    ///
156    /// let right = Motor::new(MotorPort::OutD, Direction::CounterClockwise)?;
157    ///
158    /// let left_gyro = GyroSensor::new(SensorPort::In1)?;
159    ///
160    /// let right_gyro = GyroSensor::new(SensorPort::In4)?;
161    ///
162    /// let drive = DriveBase::new(&left, &right, 62.4, 130.5)?.with_gyros(vec![ &left_gyro, &right_gyro ])?;
163    ///
164    /// // you have to explicitly enable the gyro
165    ///
166    /// drive.use_gyro(true)?;
167    /// ```
168    pub fn with_gyros<'b>(mut self, gyro_sensors: Vec<&'b GyroSensor>) -> Ev3Result<Self>
169    where
170        'b: 'a,
171    {
172        self.gyros = Some(GyroController::new(gyro_sensors)?);
173        Ok(self)
174    }
175
176    /// True makes the `DriveBase` use the gyro, while false makes the `DriveBase` use the motor encoders.
177    ///
178    /// Using the gyro is highly recommended for accurate drive actions.
179    pub fn use_gyro(&self, use_gyro: bool) -> Ev3Result<()> {
180        if use_gyro && self.gyros.is_none() {
181            return Err(Ev3Error::NoSensorProvided);
182        }
183        self.using_gyros.set(use_gyro);
184        Ok(())
185    }
186
187    /// Sets the straight speed in motor degrees per second.
188    ///
189    /// The default is 500 and the max is 1000.
190    pub fn set_straight_speed<Number>(&self, straight_speed: Number)
191    where
192        Number: ToFixed,
193    {
194        self.straight_speed.set(I32F32::from_num(straight_speed));
195    }
196
197    /// Sets the max turn speed in motor degrees per second.
198    ///
199    /// The default is 500 and the max is 1000.
200    pub fn set_turn_speed<Number>(&self, turn_speed: Number)
201    where
202        Number: ToFixed,
203    {
204        self.turn_speed.set(I32F32::from_num(turn_speed));
205    }
206
207    /// Units are in milliseconds and must be positive.
208    ///
209    /// When set to a non-zero value, the motor speed will increase from 0 to 100% of max_speed over the span of this setpoint.
210    ///
211    /// This is especially useful for avoiding wheel slip.
212    ///
213    /// The default for `DriveBase` motors 2000.
214    pub fn set_ramp_up_setpoint(&self, sp: u32) -> Ev3Result<()> {
215        self.left_motor.set_ramp_up_setpoint(sp)?;
216        self.right_motor.set_ramp_up_setpoint(sp)
217    }
218
219    /// Units are in milliseconds and must be positive.
220    ///
221    /// When set to a non-zero value, the motor speed will decrease from 0 to 100% of max_speed over the span of this setpoint.
222    ///
223    /// This is especially useful for avoiding wheel slip.
224    ///
225    /// The default for `DriveBase` motors 1800.
226    pub fn set_ramp_down_setpoint(&self, sp: u32) -> Ev3Result<()> {
227        self.left_motor.set_ramp_down_setpoint(sp)?;
228        self.right_motor.set_ramp_down_setpoint(sp)
229    }
230    /// Sets the stop action of the `DriveBase`
231    ///
232    /// Unlike pybricks, this doesn't affect whether the `DriveBase` tracks heading and distance
233    pub fn set_stop_action(&self, action: Stop) -> Ev3Result<()> {
234        self.left_motor.set_stop_action(action)?;
235        self.right_motor.set_stop_action(action)
236    }
237
238    /// Sets the distance PID settings
239    ///
240    /// default: 10, 0, 8, 0, 0
241    pub fn distance_pid_settings<Number>(
242        &self,
243        kp: Number,
244        ki: Number,
245        kd: Number,
246        integral_deadzone: Number,
247        integral_rate: Number,
248    ) where
249        Number: ToFixed,
250    {
251        self.distance_pid
252            .settings(kp, ki, kd, integral_deadzone, integral_rate);
253    }
254
255    /// Sets the heading PID settings
256    ///
257    /// default: 10, 0, 5, 0, 0
258    pub fn heading_pid_settings<Number>(
259        &self,
260        kp: Number,
261        ki: Number,
262        kd: Number,
263        integral_deadzone: Number,
264        integral_rate: Number,
265    ) where
266        Number: ToFixed,
267    {
268        self.heading_pid
269            .settings(kp, ki, kd, integral_deadzone, integral_rate);
270    }
271
272    /// Stops the `DriveBase` with the selected stop action.
273    ///
274    /// Async driving actions automatically do this
275    pub fn stop(&self) -> Ev3Result<()> {
276        self.left_motor.stop_prev_action()?;
277        self.right_motor.stop_prev_action()
278    }
279
280    async fn drive_relative(&self, distance_mm: I32F32, angle_deg: I32F32) -> Ev3Result<()> {
281        defer! {
282            _ = self.stop()
283        }
284
285        self.distance_pid.reset();
286        self.heading_pid.reset();
287
288        let target_distance = self.distance_target.get() + distance_mm;
289        let target_heading = self.heading_target.get() + angle_deg;
290
291        self.distance_target.set(target_distance);
292        self.heading_target.set(target_heading);
293
294        let mut timer = interval(Duration::from_millis(5));
295
296        // the first tick completes immediately
297        timer.tick().await;
298
299        let straight_speed = self.straight_speed.get();
300        let turn_speed = self.turn_speed.get();
301
302        loop {
303            let left_angle = I32F32::from_num(self.left_motor.angle()? - self.left_start_angle);
304            let right_angle = I32F32::from_num(self.right_motor.angle()? - self.right_start_angle);
305            let current_distance = self.encoders_to_distance(left_angle, right_angle);
306            let current_heading = if self.using_gyros.get()
307                && let Some(ref gyro) = self.gyros
308            {
309                let encoders = self.encoders_to_heading()?;
310                I32F32::from_num(gyro.heading()?) * I32F32::from_num(0.9)
311                    + encoders * I32F32::from_num(0.1)
312            } else {
313                self.encoders_to_heading()?
314            };
315
316            let distance_error = target_distance - current_distance;
317            let heading_error = target_heading - current_heading;
318
319            if distance_error.abs() < self.distance_tolerance.get()
320                && heading_error.abs() < self.heading_tolerance.get()
321            {
322                break;
323            }
324
325            let dive_effort = self.distance_pid.next(distance_error);
326            let turn_effort = -self.heading_pid.next(heading_error);
327
328            let drive_speed_out = dive_effort * straight_speed;
329            let turn_speed_out = turn_effort * turn_speed;
330
331            let left_speed = (drive_speed_out - turn_speed_out)
332                .clamp(-self.right_motor.max_speed, self.left_motor.max_speed);
333
334            let right_speed = (drive_speed_out + turn_speed_out)
335                .clamp(-self.left_motor.max_speed, self.right_motor.max_speed);
336
337            self.left_motor.run(
338                (if left_speed.abs() < self.min_speed {
339                    self.min_speed * left_speed.signum()
340                } else {
341                    left_speed
342                })
343                .lossy_into(),
344            )?;
345            self.right_motor.run(
346                (if right_speed.abs() < self.min_speed {
347                    self.min_speed * right_speed.signum()
348                } else {
349                    right_speed
350                })
351                .lossy_into(),
352            )?;
353
354            timer.tick().await;
355        }
356
357        Ok(())
358    }
359
360    /// Drives straight by the given distance in mm.
361    pub async fn straight<Number>(&self, distance: Number) -> Ev3Result<()>
362    where
363        Number: ToFixed,
364    {
365        self.drive_relative(I32F32::from_num(distance), I32F32::from_num(0))
366            .await
367    }
368
369    /// Turns by the angle in degrees.
370    pub async fn turn<Number>(&self, angle: Number) -> Ev3Result<()>
371    where
372        Number: ToFixed,
373    {
374        self.drive_relative(I32F32::from_num(0), I32F32::from_num(angle))
375            .await
376    }
377
378    /// Curves with the given radius and a target angle.
379    pub async fn curve<Number>(&self, radius: Number, angle: Number) -> Ev3Result<()>
380    where
381        Number: ToFixed,
382    {
383        let fixed_angle = I32F32::from_num(angle);
384
385        let angle_rad = fixed_angle * I32F32::PI / 180;
386        let arc_length = I32F32::from_num(radius).abs() * I32F32::from_num(angle_rad).abs();
387
388        self.drive_relative(arc_length, I32F32::from_num(fixed_angle))
389            .await
390    }
391
392    /// Turns with the given radius and distance.
393    pub async fn veer<Number>(&self, radius: Number, distance: Number) -> Ev3Result<()>
394    where
395        Number: ToFixed,
396    {
397        let fixed_distance = I32F32::from_num(distance);
398
399        let angle_rad = fixed_distance / I32F32::from_num(radius);
400        let angle_deg = angle_rad * 180 / I32F32::PI;
401
402        self.drive_relative(fixed_distance, I32F32::from_num(angle_deg))
403            .await
404    }
405
406    /// Experimental function to find the best axle track for the robot
407    ///
408    /// This should print out the ideal axle track once it is finished testing.
409    ///
410    /// If you are having trouble with inaccurate heading readings due to wheel slipping, see `set_ramp_up_setpoint`.
411    ///
412    /// Note that the value can vary wildly based on surface.
413    pub async fn find_calibrated_axle_track<Number>(
414        &mut self,
415        margin_of_error: Number,
416    ) -> Ev3Result<I32F32>
417    where
418        Number: ToFixed,
419    {
420        self.use_gyro(true)?;
421        let fixed_estimate = I32F32::from_num(self.axle_track);
422        let fixed_margin_of_error = I32F32::from_num(margin_of_error);
423        let resphi = I32F32::FRAC_1_PHI;
424
425        let mut a = fixed_estimate - fixed_margin_of_error;
426        let mut b = fixed_estimate + fixed_margin_of_error;
427        let tolerance = I32F32::from_num(0.5);
428
429        // Initial test points
430        let mut x1 = a + resphi * (b - a);
431        let mut x2 = b - resphi * (b - a);
432
433        let mut f1 = self.test_axle_track(x1).await?;
434        let mut f2 = self.test_axle_track(x2).await?;
435
436        // Golden section search loop
437        while (b - a).abs() > tolerance {
438            if f1 < f2 {
439                // Minimum is between a and x2
440                a = x2;
441                x2 = x1;
442                f2 = f1;
443                x1 = a + resphi * (b - a);
444                f1 = self.test_axle_track(x1).await?;
445            } else {
446                // Minimum is between x1 and b
447                b = x1;
448                x1 = x2;
449                f1 = f2;
450                x2 = b - resphi * (b - a);
451                f2 = self.test_axle_track(x2).await?;
452            }
453        }
454
455        let best = (a + b) / I32F32::from_num(2);
456        println!("Best axle track: {}", best);
457
458        Ok(best)
459    }
460
461    // Helper function to test a single axle track value
462    async fn test_axle_track(&mut self, candidate: I32F32) -> Ev3Result<I32F32> {
463        println!("testing {}", candidate);
464        self.axle_track = candidate;
465
466        // Reset to known position
467        if let Some(ref gyros) = self.gyros {
468            let start_encoder_heading = self.encoders_to_heading()?;
469            gyros.reset()?;
470            // Do a test turn (90 degrees)
471            self.turn(90).await?;
472
473            // Measure error
474            let gyro_turned = gyros.heading()?;
475            let encoder_turned = self.encoders_to_heading()? - start_encoder_heading;
476
477            let error = (gyro_turned - encoder_turned).abs();
478            println!("Error: {}", error);
479
480            Ok(error)
481        } else {
482            Err(Ev3Error::NoSensorProvided)
483        }
484    }
485
486    // Convert encoder positions to distance traveled (average of both wheels)
487    fn encoders_to_distance(&self, left_deg: I32F32, right_deg: I32F32) -> I32F32 {
488        let wheel_circ = I32F32::PI * self.wheel_diameter;
489        let left_mm = wheel_circ * left_deg / 360;
490        let right_mm = wheel_circ * right_deg / 360;
491        (left_mm + right_mm) / 2
492    }
493
494    /// Convert encoder positions to heading (differential between wheels)
495    fn encoders_to_heading(&self) -> Ev3Result<I32F32> {
496        let left_deg = I32F32::from_num(self.left_motor.angle()? - self.left_start_angle);
497        let right_deg = I32F32::from_num(self.right_motor.angle()? - self.right_start_angle);
498
499        let wheel_circ = I32F32::PI * self.wheel_diameter;
500        let left_mm = wheel_circ * left_deg / 360;
501        let right_mm = wheel_circ * right_deg / 360;
502        let arc_diff = left_mm - right_mm;
503        let turn_rad = arc_diff / self.axle_track;
504        let raw_heading = turn_rad * 180 / I32F32::PI;
505
506        let alpha = I32F32::from_num(0.7);
507        let filtered =
508            alpha * raw_heading + (I32F32::from_num(1) - alpha) * self.prev_encoder_heading.get();
509        self.prev_encoder_heading.set(filtered);
510        Ok(filtered)
511    }
512}