Use of PWM

For details on PWM, please refer to PWM-API Document.

Instructions

  • Import PWM and Timer modules from machine
from machine import Timer,PWM
  • Create Timer and PWM
tim = Timer(Timer.TIMER0, Timer.CHANNEL0, mode=Timer.MODE_PWM)
ch = PWM(tim, freq=500000, duty=50, pin=boad_info.LED_G)
  • Change the duty cycle, the set pin will output waveforms with different duty cycles
ch.duty(duty)

Example

Control the brightness of LED_G

board_info is related to the board, and different board configurations are different. Manual configuration is required before use.

from machine import Timer,PWM
import time
from board import board_info
from fpioa_manager import fm

tim = Timer(Timer.TIMER0, Timer.CHANNEL0, mode=Timer.MODE_PWM)
ch = PWM(tim, freq=500000, duty=50, pin=boad_info.LED_G)
duty=0
dir = True
while True:
    if dir:
        duty += 10
    else:
        duty -= 10
    if duty>100:
        duty = 100
        dir = False
    elif duty<0:
        duty = 0
        dir = True
    time.sleep(0.05)
    ch.duty(duty)