From 59e405cb884d44ee0a0a28ca5c353fa93dae9e24 Mon Sep 17 00:00:00 2001 From: Fast-Blast Date: Thu, 26 Mar 2026 18:09:12 +0100 Subject: [PATCH] Added more modularity and config. --- src/config.rs | 19 +++++++++++++++++++ src/main.rs | 42 +++++++++++++++++------------------------- src/motors.rs | 29 +++++++++++++++++++++++++++++ 3 files changed, 65 insertions(+), 25 deletions(-) create mode 100644 src/config.rs create mode 100644 src/motors.rs diff --git a/src/config.rs b/src/config.rs new file mode 100644 index 0000000..9f8bd07 --- /dev/null +++ b/src/config.rs @@ -0,0 +1,19 @@ +pub struct Config { + // Wheel GPIO pins. + pub left1: u8, + pub left2: u8, + pub right1: u8, + pub right2: u8 +} + +impl Config { + pub fn new() -> Self { + Self { + // Wheel GPIO pins. + left1: 27, + left2: 22, + right1: 23, + right2: 24 + } + } +} diff --git a/src/main.rs b/src/main.rs index 2f5fa63..d42e06f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,34 +1,26 @@ -use rppal::gpio::{Gpio, OutputPin}; +// External libraries. +use rppal::gpio::{Gpio}; use rppal::pwm::{Pwm, Channel, Polarity}; use std::{error::Error, thread, time::Duration}; -struct Motor { - in1: OutputPin, - in2: OutputPin, - pwm: Pwm, -} +// Own libraries. +mod motors; +use motors::Motor; -impl Motor { - fn forward(&mut self, speed: f64) { - self.in1.set_high(); - self.in2.set_low(); - self.pwm.set_duty_cycle(speed).unwrap(); - } - - fn backward(&mut self, speed: f64) { - self.in1.set_low(); - self.in2.set_high(); - self.pwm.set_duty_cycle(speed).unwrap(); - } - - fn stop(&mut self) { - self.in1.set_low(); - self.in2.set_low(); - self.pwm.set_duty_cycle(0.0).unwrap(); - } -} +// Config +mod config; +use config::Config; fn main() -> Result<(), Box> { + let config = Config::new(); + println!( + "Starting with GPIO pins:\n - Motors\n - Right 1: {}\n - Right 2: {}\n - Left 1: {}\n - Left 2: {}", + config.right1, + config.right2, + config.left1, + config.left2 + ); + let gpio = Gpio::new()?; // LEFT diff --git a/src/motors.rs b/src/motors.rs new file mode 100644 index 0000000..33430a4 --- /dev/null +++ b/src/motors.rs @@ -0,0 +1,29 @@ +use rppal::gpio::OutputPin; +use rppal::pwm::Pwm; + +pub struct Motor { + pub in1: OutputPin, + pub in2: OutputPin, + pub pwm: Pwm, +} + + +impl Motor { + pub fn forward(&mut self, speed: f64) { + self.in1.set_high(); + self.in2.set_low(); + self.pwm.set_duty_cycle(speed).unwrap(); + } + + pub fn backward(&mut self, speed: f64) { + self.in1.set_low(); + self.in2.set_high(); + self.pwm.set_duty_cycle(speed).unwrap(); + } + + pub fn stop(&mut self) { + self.in1.set_low(); + self.in2.set_low(); + self.pwm.set_duty_cycle(0.0).unwrap(); + } +}