Class PWM – Pulse Width Modulation

Pulse Width Modulation (PWM) is a technique for getting analog results with digital means.

Constructors

class machine.PWM(pin, freq, duty)

Create a PWM object associated with the specified pin. This allows you to write analog values on that pin.

  • pin Pins that support PWM: GPIO0, GPIO2, GPIO4, GPIO5, GPIO10, GPIO12~19, GPIO21, GPIO22, GPIO23, GPIO25~27. See ESP32 Pinout Table.

  • freq Frequency, 0 < freq <= 78125 Hz

  • duty Duty cycle, 0 <= duty <= 0x03FF (decimal: 0 <= duty <= 1023)

Important

PWM can be enabled on all output pins. However, it has limitations: all channels must use the same frequency, and there are only 8 channels available.

Example:

from machine import PWM, Pin

pwm = PWM (Pin(2), freq=1000,  duty=1023)    # create an PWM object

Methods

PWM.init(freq, duty)

Initialize PWM. freq and duty are as described above.

Example:

pwm.init(1000, 500)
PWM.freq([freq_val])

When called without arguments, returns the PWM frequency. When called with an argument, sets the PWM frequency. No return value when setting.

  • freq_val PWM frequency, 0 < freq <= 0x0001312D (decimal: 0 < freq <= 78125 Hz)

Example:

print(pwm.freq())
print(pwm.freq(2000)
PWM.duty([duty_val])

When called without arguments, returns the PWM duty cycle. When called with an argument, sets the PWM duty cycle.

  • duty_val Duty cycle, 0 <= duty <= 0x03FF (decimal: 0 <= duty_val <= 1023)

Example:

>>> print(pwm.duty())
50
>>> print(pwm.duty(500))
None
PWM.deinit()

Disable PWM. After using PWM, you need to call deinit() to release it.