Start adding rust car implementation

This commit is contained in:
piv
2022-07-31 16:05:39 +09:30
parent ba942804db
commit 825f57dee9
5 changed files with 980 additions and 1 deletions

56
car-rs/src/lib.rs Normal file
View File

@@ -0,0 +1,56 @@
use rppal::pwm::{Channel, Pwm};
pub trait Servo {
fn get_duty_cycle(&self) -> f64;
// TODO: Some kind of error handling here, in case we fail to set the duty cycel
fn set_duty_cycle(&self, pwm: f64);
fn get_frequency(&self) -> f64;
fn set_frequency(&self, frequency: f64);
}
pub trait Vechicle<T: Servo> {
fn get_throttle_servo() -> T;
fn get_steering_servo() -> T;
}
pub struct RpiPwmServo {
pwm: Pwm,
}
impl RpiPwmServo {
pub fn new(pwm: Pwm) -> RpiPwmServo {
RpiPwmServo { pwm }
}
}
impl Default for RpiPwmServo {
fn default() -> Self {
Self {
pwm: Pwm::new(Channel::Pwm0).expect("Failed to initialise Pwm servo"),
}
}
}
impl Servo for RpiPwmServo {
fn get_duty_cycle(&self) -> f64 {
self.pwm.duty_cycle().unwrap_or(0.)
}
fn set_duty_cycle(&self, pwm: f64) {
self.pwm
.set_duty_cycle(pwm)
.expect("Failed to write duty cycle");
}
fn get_frequency(&self) -> f64 {
self.pwm.duty_cycle().unwrap_or(0.0)
}
fn set_frequency(&self, frequency: f64) {
self.pwm
.set_frequency(frequency, self.get_duty_cycle())
.expect("Failed to set Frequency")
}
}