【MicroPython】machine.PWM Function

From Waveshare Wiki
Jump to: navigation, search
  • machine.PWM(pins):
    • PWM object constructor
    • pin: GPIO object that needs to be set as PWM output;

Its function will reinitialize the specified GPIO and set it to PWM output mode.

The first parameter pin is the Pin object explained in the previous tutorial, which is used to specify the use of GPIO, and the object will be reinitialized.

  • PWM.deinit():
    • Cancel PWM initialization.

deinit is a deinitialization function whose function is to clear initialization and stop PWM output.

  • PWM.freq([value]):
    • Sets the PWM output frequency function.
    • value: PWM output frequency, the value should conform to the PWM frequency calculation formula;

The freq function is a PWM frequency setting function that automatically calculates the frequency divider parameter (frequency division factor) and the TOP register parameter (counter maximum count value) according to the parameter value.

  • PWM.duty_u16([value]):
    • Set the counter comparison value,
    • value: Set the duty ratio, the value should be between 0-65536;

The duty_u16 function is used to set the duty cycle. Through the parameter value, the corresponding value will be automatically calculated and given to the CC register. When the counter count value is smaller than the CC register, the PWM pin outputs a high level, otherwise it outputs a low level.

  • PWM.duty_ns([value]):
    • Set the time of high level;
    • value: Set the high level time, the unit is ns;

The role of the duty_ns function is to set the duration of a cycle to output a high level. Its parameter value is the high level time in ns.
This article is only for RP2040 MicroPython firmware, and the source code shall prevail. This article is written according to the official source code at the time of writing, which is used to provide convenience for beginners and is for reference only. Those who are capable are recommended to refer to MicroPython.