raslib/
l298n.rs

1// This file is part of "raslib"
2// Under the MIT License
3// Copyright (c) Antonin Hérault
4
5use crate::Gpio;
6use crate::{HIGH, LOW};
7
8use std::io;
9
10/// Controls a L298N circuit motor connected on GPIO ports.
11///
12/// Get an advanced explanations about L298N circuit motors on
13/// https://www.dprg.org/l298n-motor-driver-board-drive-modes/.
14#[derive(Debug, Clone, Copy)]
15pub struct L298n {
16    /// Pin for the direction settings as well as `in2`.
17    in1: Gpio,
18    /// Pin for the direction settings as well as `in1`.
19    in2: Gpio,
20    /// Pin to modulate the speed of the motor.
21    ena: Gpio,
22}
23
24impl L298n {
25    /// Creates a new [`L298n`] object for a motor on three GPIO pins from
26    /// their number.
27    pub fn new(in1: u32, in2: u32, ena: u32) -> Self {
28        Self {
29            in1: Gpio::new(in1).unwrap(),
30            in2: Gpio::new(in2).unwrap(),
31            ena: Gpio::new(ena).unwrap(),
32        }
33    }
34
35    /// Sets the first direction pin to high and the second to low.
36    ///
37    /// Sets the speed pin to high in order to activate the motor.
38    pub fn forward(&mut self) -> Result<(), io::Error> {
39        self.in1.write(HIGH)?;
40        self.in2.write(LOW)?;
41        self.ena.write(HIGH)
42    }
43
44    /// Sets the first direction pin to low and the second to high.
45    ///
46    /// Sets the speed pin to high in order to activate the motor.
47    pub fn backward(&mut self) -> Result<(), io::Error> {
48        self.in1.write(LOW)?;
49        self.in2.write(HIGH)?;
50        self.ena.write(HIGH)
51    }
52
53    /// Sets the speed pin to low in order to deactivate the motor.
54    pub fn stop(&mut self) -> Result<(), io::Error> {
55        self.ena.write(LOW)
56    }
57}