class PWM – pulse width modulation — MicroPython latest documentation (original) (raw)

This is the documentation for the latest development branch of MicroPython and may refer to features that are not available in released versions.

If you are looking for the documentation for a specific release, use the drop-down menu on the left and select the desired version.

This class provides pulse width modulation output.

Example usage:

from machine import PWM

pwm = PWM(pin, freq=50, duty_u16=8192) # create a PWM object on a pin # and set freq and duty pwm.duty_u16(32768) # set duty to 50%

reinitialise with a period of 200us, duty of 5us

pwm.init(freq=5000, duty_ns=5000)

pwm.duty_ns(3000) # set pulse width to 3us

pwm.deinit()

Constructors

class machine.PWM(dest, *, freq, duty_u16, duty_ns, invert)

Construct and return a new PWM object using the following parameters:

Setting freq may affect other PWM objects if the objects share the same underlying PWM generator (this is hardware specific). Only one of duty_u16 and duty_ns should be specified at a time.invert is not available at all ports.

Methods

PWM.init(*, freq, duty_u16, duty_ns)

Modify settings for the PWM object. See the above constructor for details about the parameters.

PWM.deinit()

Disable the PWM output.

PWM.freq([_value_])

Get or set the current frequency of the PWM output.

With no arguments the frequency in Hz is returned.

With a single value argument the frequency is set to that value in Hz. The method may raise a ValueError if the frequency is outside the valid range.

PWM.duty_u16([_value_])

Get or set the current duty cycle of the PWM output, as an unsigned 16-bit value in the range 0 to 65535 inclusive.

With no arguments the duty cycle is returned.

With a single value argument the duty cycle is set to that value, measured as the ratio value / 65535.

PWM.duty_ns([_value_])

Get or set the current pulse width of the PWM output, as a value in nanoseconds.

With no arguments the pulse width in nanoseconds is returned.

With a single value argument the pulse width is set to that value.

Specific PWM class implementations

The following concrete class(es) implement enhancements to the PWM class.

Limitations of PWM