From 934e169e7d618a4bda6dc421fe230fdba6ece01d Mon Sep 17 00:00:00 2001 From: Joakim Hulthe Date: Sun, 25 Oct 2026 22:42:30 +0100 Subject: [PATCH] Add different step modes for better torque --- example.motor.toml | 6 ++++-- src/motor.rs | 52 +++++++++++++++++++++++++++++++++++++++------- 2 files changed, 49 insertions(+), 9 deletions(-) diff --git a/example.motor.toml b/example.motor.toml index b826016..a722c2b 100644 --- a/example.motor.toml +++ b/example.motor.toml @@ -1,2 +1,4 @@ -pin_mappings = [0, 2, 3, 4] -sleep_time = { secs = 0, nanos = 7_000_000 } + +pin_mappings = [17, 27, 22, 23] +sleep_time = { secs = 0, nanos = 5_000_000 } +step_mode = "OneTwo" # or "One" or "Two" diff --git a/src/motor.rs b/src/motor.rs index 9cdea87..0edf4ab 100644 --- a/src/motor.rs +++ b/src/motor.rs @@ -9,6 +9,7 @@ use std::time::Duration; pub struct Motor { pins: MotorPins, sleep_time: Duration, + step_mode: StepModePhase, } #[derive(Clone, Debug, Serialize, Deserialize)] @@ -17,6 +18,16 @@ pub struct MotorConfig { /// The time in milliseconds between each tick of the stepper motor pub sleep_time: Duration, + + /// The time in milliseconds between each tick of the stepper motor + pub step_mode: StepModePhase, +} + +#[derive(Clone, Copy, Debug, Serialize, Deserialize)] +pub enum StepModePhase { + OneTwo, + Two, + One, } pub struct MotorPins { @@ -52,18 +63,45 @@ impl Motor { Ok(Motor { sleep_time: config.sleep_time, pins, + step_mode: config.step_mode, }) } pub fn spin_step(&mut self, direction: Direction) { - let mut pin_states = [High, Low, Low, Low]; + let phases = match self.step_mode { + StepModePhase::One => &[ + [Low, High, Low, Low], + [Low, Low, High, Low], + [Low, Low, Low, High], + [High, Low, Low, Low], + ][..], + StepModePhase::Two => &[ + [Low, High, High, Low], + [Low, Low, High, High], + [High, Low, Low, High], + [High, High, Low, Low], + ], + StepModePhase::OneTwo => &[ + [High, High, Low, Low], + [Low, High, Low, Low], + [Low, High, High, Low], + [Low, Low, High, Low], + [Low, Low, High, High], + [Low, Low, Low, High], + [High, Low, Low, High], + [High, Low, Low, Low], + ], + }; - for _ in 0..pin_states.len() { - self.pins.set(pin_states); - match direction { - Direction::Right => pin_states.rotate_right(1), - Direction::Left => pin_states.rotate_left(1), - } + match direction { + Direction::Left => self.spin_step_inner(phases.iter().copied().rev()), + Direction::Right => self.spin_step_inner(phases.iter().copied()), + } + } + + fn spin_step_inner(&mut self, phases: impl Iterator) { + for levels in phases { + self.pins.set(levels); sleep(self.sleep_time); } }