diff --git a/src/core/motor.rs b/src/core/motor.rs index 75dd963..1697dbd 100644 --- a/src/core/motor.rs +++ b/src/core/motor.rs @@ -2,11 +2,9 @@ use core::fmt::Display; use serde::{Deserialize, Serialize}; -use crate::core::units::{ - Current, - Voltage, - Angle, -}; +use crate::core::{motor::Direction::{CCW, CW}, units::{ + Angle, Current, Voltage +}}; ///A simple enum for Counterclockwise or Clockwise direction semantics. Makes it easier much clear than a true/false bool #[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)] @@ -28,7 +26,45 @@ impl Direction { } } - + ///Changes the current direction based on the sign of the float. + ///Recommended to use this over the "From" impl for directions that already exist, to prevent werid 0.0 case and NaN problems + /// This handles 0.0 and NaN by just doing nothing. The "From" impl defualts to CCW for both + pub fn dir_from_f32(&mut self, value: f32) { + if value == 0.0 || value.is_nan() { return; } + *self = value.into(); + } + + ///Changes the current direction based on the sign of the int. + ///Recommended to use this over the "From" impl for directions that already exist, to prevent weird 0 case problems + ///This handles 0 by just doing nothing. The "From" impl defaults to CCW + pub fn dir_from_i32(&mut self, value: i32) { + if value == 0 { return; } + *self = value.into(); + } +} + +///Converts F32 to direction using the number's sign. +/// This defaults to CCW for 0.0 and NaN. +impl From for Direction { + fn from(value: f32) -> Self { + if value < 0.0 { + CW + } else { + CCW + } + } +} + +/// Converts i32 to direction using the number's sign. +/// This defaults to CCW for 0. +impl From for Direction { + fn from(value: i32) -> Self { + if value < 0 { + CW + } else { + CCW + } + } } ///A enum for containerizing speeds easily