esp-rs / esp-idf-hal

embedded-hal implementation for Rust on ESP32 and ESP-IDF
https://docs.esp-rs.org/esp-idf-hal/
Apache License 2.0
456 stars 171 forks source link

Need to change PWM frequency of LedcDriver #294

Closed Angelo13C closed 1 year ago

Angelo13C commented 1 year ago

Hi!

I need to change the PWM frequency of LedcDriver after it has been created because the TMC2209 motor driver needs a clock signal on the STEP pin that moves the motor one step for each rising edge.

The problem now is that after creating a LedcDriver there's no way to change its frequency so there's no way to change the speed of the motor.

I thought about adding this:

/// Set the frequency of the timer.
pub fn set_frequency(&mut self, frequency: Hertz) -> Result<(), EspError> {
    esp!(unsafe {
        ledc_set_freq(self.speed_mode.into(), self.timer.into(), frequency.into())
    })?;
    Ok(())
}

in LedcDriver but I don't know if it's safe

Vollbrecht commented 1 year ago

The LEDC hardware is somewhat limited if you want to change the frequency at runtime. That is duo to the fact that each of the 4 timers is shared with multiple channels. So if you are using timer 0 and channel 0 and 1, you will change the frequency of both channels 0 and 1 at the same time because they are bound to timer 0. So what they recommend is :

We don't implement the swapping the channels currently in the wrapper, if i am not mistaken, so you would need to go with method one currently.