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 is 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 is 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 functions automatically do this.
275    ///
276    /// See `set_stop_action` to select the stop action.
277    pub fn stop(&self) -> Ev3Result<()> {
278        self.left_motor.stop_prev_action()?;
279        self.right_motor.stop_prev_action()
280    }
281
282    async fn drive_relative(&self, distance_mm: I32F32, angle_deg: I32F32) -> Ev3Result<()> {
283        defer! {
284            _ = self.stop()
285        }
286
287        self.distance_pid.reset();
288        self.heading_pid.reset();
289
290        let target_distance = self.distance_target.get() + distance_mm;
291        let target_heading = self.heading_target.get() + angle_deg;
292
293        self.distance_target.set(target_distance);
294        self.heading_target.set(target_heading);
295
296        let mut timer = interval(Duration::from_millis(5));
297
298        // the first tick completes immediately
299        timer.tick().await;
300
301        let straight_speed = self.straight_speed.get();
302        let turn_speed = self.turn_speed.get();
303
304        loop {
305            let left_angle = I32F32::from_num(self.left_motor.angle()? - self.left_start_angle);
306            let right_angle = I32F32::from_num(self.right_motor.angle()? - self.right_start_angle);
307            let current_distance = self.encoders_to_distance(left_angle, right_angle);
308            let current_heading = if self.using_gyros.get()
309                && let Some(ref gyro) = self.gyros
310            {
311                let encoders = self.encoders_to_heading()?;
312                I32F32::from_num(gyro.heading()?) * I32F32::from_num(0.9)
313                    + encoders * I32F32::from_num(0.1)
314            } else {
315                self.encoders_to_heading()?
316            };
317
318            let distance_error = target_distance - current_distance;
319            let heading_error = target_heading - current_heading;
320
321            if distance_error.abs() < self.distance_tolerance.get()
322                && heading_error.abs() < self.heading_tolerance.get()
323            {
324                break;
325            }
326
327            let dive_effort = self.distance_pid.next(distance_error);
328            let turn_effort = -self.heading_pid.next(heading_error);
329
330            let drive_speed_out = dive_effort * straight_speed;
331            let turn_speed_out = turn_effort * turn_speed;
332
333            let left_speed = (drive_speed_out - turn_speed_out)
334                .clamp(-self.right_motor.max_speed, self.left_motor.max_speed);
335
336            let right_speed = (drive_speed_out + turn_speed_out)
337                .clamp(-self.left_motor.max_speed, self.right_motor.max_speed);
338
339            self.left_motor.run(
340                (if left_speed.abs() < self.min_speed {
341                    self.min_speed * left_speed.signum()
342                } else {
343                    left_speed
344                })
345                .lossy_into(),
346            )?;
347            self.right_motor.run(
348                (if right_speed.abs() < self.min_speed {
349                    self.min_speed * right_speed.signum()
350                } else {
351                    right_speed
352                })
353                .lossy_into(),
354            )?;
355
356            timer.tick().await;
357        }
358
359        Ok(())
360    }
361
362    /// Drives straight by the given distance in mm.
363    pub async fn straight<Number>(&self, distance: Number) -> Ev3Result<()>
364    where
365        Number: ToFixed,
366    {
367        self.drive_relative(I32F32::from_num(distance), I32F32::from_num(0))
368            .await
369    }
370
371    /// Turns by the angle in degrees.
372    pub async fn turn<Number>(&self, angle: Number) -> Ev3Result<()>
373    where
374        Number: ToFixed,
375    {
376        self.drive_relative(I32F32::from_num(0), I32F32::from_num(angle))
377            .await
378    }
379
380    /// Curves with a given radius and a target angle.
381    pub async fn curve<Number>(&self, radius: Number, angle: Number) -> Ev3Result<()>
382    where
383        Number: ToFixed,
384    {
385        let fixed_angle = I32F32::from_num(angle);
386
387        let angle_rad = fixed_angle * I32F32::PI / 180;
388        let arc_length = I32F32::from_num(radius).abs() * I32F32::from_num(angle_rad).abs();
389
390        self.drive_relative(arc_length, I32F32::from_num(fixed_angle))
391            .await
392    }
393
394    /// Curves with a given radius and distance.
395    pub async fn veer<Number>(&self, radius: Number, distance: Number) -> Ev3Result<()>
396    where
397        Number: ToFixed,
398    {
399        let fixed_distance = I32F32::from_num(distance);
400
401        let angle_rad = fixed_distance / I32F32::from_num(radius);
402        let angle_deg = angle_rad * 180 / I32F32::PI;
403
404        self.drive_relative(fixed_distance, I32F32::from_num(angle_deg))
405            .await
406    }
407
408    /// Experimental function to find the best axle track for the robot
409    ///
410    /// This should print out the ideal axle track once it is finished testing.
411    ///
412    /// If you are having trouble with inaccurate heading readings due to wheel slipping, see `set_ramp_up_setpoint`.
413    ///
414    /// Note that the output value can vary wildly based on surface.
415    pub async fn find_calibrated_axle_track<Number>(
416        &mut self,
417        margin_of_error: Number,
418    ) -> Ev3Result<I32F32>
419    where
420        Number: ToFixed,
421    {
422        self.use_gyro(true)?;
423        let fixed_estimate = I32F32::from_num(self.axle_track);
424        let fixed_margin_of_error = I32F32::from_num(margin_of_error);
425        let resphi = I32F32::FRAC_1_PHI;
426
427        let mut a = fixed_estimate - fixed_margin_of_error;
428        let mut b = fixed_estimate + fixed_margin_of_error;
429        let tolerance = I32F32::from_num(0.5);
430
431        // Initial test points
432        let mut x1 = a + resphi * (b - a);
433        let mut x2 = b - resphi * (b - a);
434
435        let mut f1 = self.test_axle_track(x1).await?;
436        let mut f2 = self.test_axle_track(x2).await?;
437
438        // Golden section search loop
439        while (b - a).abs() > tolerance {
440            if f1 < f2 {
441                // Minimum is between a and x2
442                a = x2;
443                x2 = x1;
444                f2 = f1;
445                x1 = a + resphi * (b - a);
446                f1 = self.test_axle_track(x1).await?;
447            } else {
448                // Minimum is between x1 and b
449                b = x1;
450                x1 = x2;
451                f1 = f2;
452                x2 = b - resphi * (b - a);
453                f2 = self.test_axle_track(x2).await?;
454            }
455        }
456
457        let best = (a + b) / I32F32::from_num(2);
458        println!("Best axle track: {}", best);
459
460        Ok(best)
461    }
462
463    // Helper function to test a single axle track value
464    async fn test_axle_track(&mut self, candidate: I32F32) -> Ev3Result<I32F32> {
465        println!("testing {}", candidate);
466        self.axle_track = candidate;
467
468        // Reset to known position
469        if let Some(ref gyros) = self.gyros {
470            let start_encoder_heading = self.encoders_to_heading()?;
471            gyros.reset()?;
472            // Do a test turn (90 degrees)
473            self.turn(90).await?;
474
475            // Measure error
476            let gyro_turned = gyros.heading()?;
477            let encoder_turned = self.encoders_to_heading()? - start_encoder_heading;
478
479            let error = (gyro_turned - encoder_turned).abs();
480            println!("Error: {}", error);
481
482            Ok(error)
483        } else {
484            Err(Ev3Error::NoSensorProvided)
485        }
486    }
487
488    // Convert encoder positions to distance traveled (average of both wheels)
489    fn encoders_to_distance(&self, left_deg: I32F32, right_deg: I32F32) -> I32F32 {
490        let wheel_circ = I32F32::PI * self.wheel_diameter;
491        let left_mm = wheel_circ * left_deg / 360;
492        let right_mm = wheel_circ * right_deg / 360;
493        (left_mm + right_mm) / 2
494    }
495
496    // Convert encoder positions to heading (differential between wheels)
497    fn encoders_to_heading(&self) -> Ev3Result<I32F32> {
498        let left_deg = I32F32::from_num(self.left_motor.angle()? - self.left_start_angle);
499        let right_deg = I32F32::from_num(self.right_motor.angle()? - self.right_start_angle);
500
501        let wheel_circ = I32F32::PI * self.wheel_diameter;
502        let left_mm = wheel_circ * left_deg / 360;
503        let right_mm = wheel_circ * right_deg / 360;
504        let arc_diff = left_mm - right_mm;
505        let turn_rad = arc_diff / self.axle_track;
506        let raw_heading = turn_rad * 180 / I32F32::PI;
507
508        let alpha = I32F32::from_num(0.7);
509        let filtered =
510            alpha * raw_heading + (I32F32::from_num(1) - alpha) * self.prev_encoder_heading.get();
511        self.prev_encoder_heading.set(filtered);
512        Ok(filtered)
513    }
514}