KevsRobots Learning Platform
By Kevin McAleer, 2 Minutes
Time to put PWM to work. In this lesson you’ll wire up an LED and make it fade smoothly up and down.
GP15 (physical pin 20) to one end of the 220Ω resistorGND pinThe resistor limits the current so the LED and the Pico pin aren’t damaged.
Before using PWM, check the wiring with a plain digital output:
from machine import Pin
led = Pin(15, Pin.OUT)
led.value(1)
from machine import Pin, PWM
from time import sleep
led = PWM(Pin(15))
led.freq(1000)
while True:
# fade up
for duty in range(0, 65536, 1024):
led.duty_u16(duty)
sleep(0.01)
# fade down
for duty in range(65535, -1, -1024):
led.duty_u16(duty)
sleep(0.01)
led.freq(1000) switches the LED on and off 1000 times a second, far too fast to seeBrightness isn’t linear
Your eyes notice changes at low brightness much more than at high brightness, so the fade looks quick at the start and slow at the end. Squaring the value (
led.duty_u16(duty * duty // 65535)) gives a smoother-looking fade.
Add a potentiometer later in the course (lesson 9) and use its reading to set the LED brightness directly.
Quick quiz 1 of 2
Why does the LED need a resistor?
Quick quiz 2 of 2
Which leg of the LED goes towards GND?
You can use the arrows ← → on your keyboard to navigate between lessons.
Comments