given the same frequency, why does the pwm period decrease when the resolution decreases

209 Views Asked by At

I've got an ESP32-C3 and the following Rust code. Retaining the frequency but decreasing the resolution, I expected the accuracy of the pulse width to decrease but it unfortunately also decreases the period (speeds up). I expected the period to stay the same as I thought it is fully determined by the frequency and not by the resolution.

let pwm_pin = peripherals.pins.gpio10.into_output().unwrap();
let config = TimerConfig::default().frequency((50.Hz()).into()).resolution(Resolution::Bits13);
let timer = Timer::new(peripherals.ledc.timer0, &config)?;
let mut channel = Channel::new(peripherals.ledc.channel0, &timer, pwm_pin)?;

// set duty cycle to 50%
let percent = 50;
let duty = ((channel.get_max_duty() as f64 / 100.0) * percent as f64) as u32;
channel.set_duty(duty);

13bit produce a PWM period of 20ms, duty cycle of 50% and a high pulse width of 10ms.

Resolution::Bits13

Decreasing the resolution to Resolution::Bits8 has the unexpected effect of not just reducing the duty cycle granularity but also decreasing the period.

8bit produce a PWM period of 250us, duty cycle of 50% and a high pulse width of 124us.

Resolution::Bits8

How do I calculate the period from any given frequency and resolution. All I found online is references to period = 1/frequency which does not take the resolution into account.

1

There are 1 best solutions below

0
On

Someone on GitHub lifted the veil on what is going on here...

A simple reverse calculation: 8bit -> 255 = 250us | x = 20ms => x = y > * 20ms/250us => y = 80 & x = 20400. Because 20400 > 13Bits our initial assumption that 255 = 250us was not true but already a bit lower. but its still a factor of 80 down. the problem with low frequency's compared to high input clocks is you either need a high resolution counter ( eg many bits) or divide down your clock source further otherwise you fill your register to fast. ( counting to 255 is faster than counting to 20400 with the same counting speed) but sometimes you are hardware limited and can not reach all desired output speeds ( you are already dividing down your input clock by max divider). So if it hits a hardware limit and cant translate it it has to for example rise the frequency respectively.

Link to the discussion https://github.com/esp-rs/esp-idf-sys/issues/154