PWM - LED fade and Blink

Materials

  • AmebaD [ AMB23 / AMB21 / AMB22 / BW16 / BW16-TypeC ] x 1
  • LED x 1
  • Resistor(220ohm) x 1

Example

PWM use pulse width modulation to control output duty cycle and is widely used to control LED brightness and motor. Here we are using an LED to demonstrate how PWM works.

Code

Copy and execute each line one by one to see the LED gradually bright up and blink.

from machine import Pin, PWM
p = PWM("PA_26")
# 0 duty cycle thus output 0
p.duty_u16 (0)
# 10% duty cycle
p.duty_u16 (6553)
# 50% duty cycle
p.duty_u16(32768)
# 100% duty cycle
p.duty_u16 (65535)
# 20 Hz at 50% duty cycle, LED blinking
p.duty_u16 (32768)
p.freq(20)
Please confirm that QQ communication software is installed