class PWM – pulse width modulation
Pulse width modulation (PWM) is a technique for obtaining analog results using digital means.
Constructors
- class machine.PWM(pin, freq, duty)
Create a PWM object associated with the given pin. This allows you to write analog values to the pin.
pinis a pin object that supports PWM. The ESP32 supports PWM on pinsGPIO0,GPIO2,GPIO4,GPIO5,GPIO10,GPIO12~19,GPIO21,GPIO22,GPIO23,GPIO25~27. See ESP32 pin assignment.freqis the frequency, 0 < freq <= 78125 Hzdutyis the duty cycle, 0 ≤ duty ≤ 0x03FF (decimal: 0 ≤ duty ≤ 1023)
Important
PWM can be enabled on all output pins. However, there are some limitations: all PWM must have the same frequency, and there are only 8 channels.
Example:
from machine import PWM, Pin
pwm = PWM (Pin(2), freq=1000, duty=1023) # Create a PWM object
Methods
- PWM.init(freq, duty)
Initialize the PWM with the given frequency and duty cycle.
Example:
pwm.init(1000, 500)
- PWM.freq([freq_val])
When no argument is given, this function gets and returns the PWM frequency. When an argument is given, this function sets the PWM frequency and returns nothing.
freq_valis the PWM frequency, 0 < freq ≤ 0x0001312D (decimal: 0 < freq ≤ 78125 Hz)
Example:
print(pwm.freq())
print(pwm.freq(2000)
- PWM.duty([duty_val])
When no argument is given, this function gets and returns the PWM duty cycle. When an argument is given, this function sets the PWM duty cycle.
duty_valis the duty cycle, 0 ≤ duty ≤ 0x03FF (decimal: 0 ≤ duty_val ≤ 1023)
Example:
>>> print(pwm.duty())
50
>>> print(pwm.duty(500))
None
- PWM.deinit()
Turn off the PWM. After using PWM, you need to use
deinit()to deinitialize it.