Skip to content

How to modify duty cycle or frequency or period in timer callback #16281

Answered by sosi-deadeye
mogplus88 asked this question in ESP32
Discussion options

You must be logged in to vote

The PWM object also has the init method: https://docs.micropython.org/en/latest/library/machine.PWM.html#machine.PWM.init
In 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:

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)

Result:

Replies: 2 comments 3 replies

Comment options

You must be logged in to vote
2 replies
@mogplus88
Comment options

@robert-hh
Comment options

Comment options

You must be logged in to vote
1 reply
@mogplus88
Comment options

Answer selected by mogplus88
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
ESP32
Labels
None yet
3 participants