Skip to content

Commit

Permalink
src: lib: Add set_pwm_channel_duty_cycle
Browse files Browse the repository at this point in the history
  • Loading branch information
RaulTrombin committed Feb 17, 2024
1 parent 8261178 commit 1ccb399
Showing 1 changed file with 47 additions and 0 deletions.
47 changes: 47 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -469,6 +469,53 @@ impl Navigator {
self.pwm.set_channel_off(channel.into(), value).unwrap();
}

/// Sets the Duty Cycle (high value time) of selected channel.
///
/// On PCA9685, this function sets the `OFF` counter and uses ON value as 0.
///
/// # Further info
/// Check **[7.3.3 LED output and PWM control](https://www.nxp.com/docs/en/data-sheet/PCA9685.pdf#page=16)**
///
/// # Examples
///
/// ```no_run
/// use navigator_rs::{Navigator, PwmChannel};
///
/// let mut nav = Navigator::new();
///
/// nav.init();
/// nav.set_pwm_enable(true);
///
/// nav.set_pwm_freq_prescale(99); // sets the pwm frequency to 60 Hz
/// nav.set_pwm_channel_duty_cycle(PwmChannel::Ch1, 50.0); // sets the duty cycle to 50%
/// ```
pub fn set_pwm_channel_duty_cycle(&mut self, channel: PwmChannel, duty_cycle: f32) {
let max_duty_cycle = 100.0;
let max_value = 4095;

if duty_cycle >= 100.0 {
if duty_cycle > 100.0 {
warn!(
"Invalid duty cycle. Duty cycle must be less than or equal to 10, using 100."
);
};
self.pwm.set_channel_full_on(channel.into(), 0).unwrap();
return;
}

let duty_cycle = if duty_cycle < 0.0 {
warn!("Invalid duty cycle. Duty cycle must be non-negative, using 0.");
0.0
} else {
duty_cycle
};

let value = (duty_cycle / max_duty_cycle * max_value as f32) as u16;

self.pwm.set_channel_on(channel.into(), 0).unwrap();
self.pwm.set_channel_off(channel.into(), value).unwrap();
}

/// Like [`set_pwm_channel_value`](struct.Navigator.html#method.set_pwm_channel_value). This function
/// sets the Duty Cycle for a list of multiple channels.
///
Expand Down

0 comments on commit 1ccb399

Please sign in to comment.