How to modify duty cycle or frequency or period in timer callback #16281
-
I must have missed something somewhere. How can the mark/space ratio of a PWM stream be set in an ESP32 timer? All I can see is freq and period, which are nearly synonyms for each other anyway. If I wanted to fade a led or set led brightness with an ESP32 timer, how would I do it? Thanks. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
The Example: from machine import Timer
def handler1(timer):
print("[handler1]: Function triggered by timer", timer)
timer.init(callback=handler2, freq=1)
def handler2(timer):
print("[handler2]: Function triggered by timer", timer)
t1 = Timer(1)
t1.init(mode=Timer.PERIODIC, freq=1, callback=handler1) |
Beta Was this translation helpful? Give feedback.
-
The Code: from machine import Pin, PWM
ON_TIME_US = 2_000
OFF_TIME_US = 300
FREQ = int(1_000_000 / (ON_TIME_US + OFF_TIME_US))
DUTY = int((OFF_TIME_US / ON_TIME_US) * 65535)
pwm1 = PWM(Pin(16), freq=FREQ, duty_u16=DUTY) |
Beta Was this translation helpful? Give feedback.
The
PWM
object also has theinit
method: https://docs.micropython.org/en/latest/library/machine.PWM.html#machine.PWM.initIn the handler/callback you can change the configuration of the PWM instance.
You could set frequency and duty cycle to get high for 2000 µs and low for 300 µs. Timers are using milliseconds.
Code:
Result: