We will use LEDs to show an analogue output. As the value changes from 0 to 65535 the brightness of the LED will increase.
The pico can’t do a proper analogue output. In other words, it can’t vary the voltage on a output pin. It can only do a digital output. But it can simulate an analogue output using a technique called pulse width modulation (PWM). This turns a digital signal on and off really quickly. By varying the relative on and off time, we can simulate analogue control of certain components such as leds.
All the GP pins on the pico can provide a PWM signal.
Wire up the LED using a 220ohm resistor like this. The resistor limits the current so the LED does not burn out. This is identical to how we wired up the LED for digital control.
Circuit | Pico |
---|---|
Black | GND |
Yellow | GP16 or another GP pin |
Write this code and download to the Pico. The LED should go from off to full intensity in a smooth transition.
See code on github# Test PWM brightness control on an LED
import time
import board
import analogio
import pwmio
# Set up the LED on pin 13 as an analogue output pin
led = pwmio.PWMOut(board.GP13, frequency=1000)
# Loop forever adjusting the LED brightness in the range 0 (off) to 65535 (full on)
while True:
for brightness in range(0,65535,1000):
led.duty_cycle = brightness
time.sleep(0.1)
Note that because of the way the PWM pins are wired up, certain pairs of pins can't be used together. In the diagram below, pins with the same letter and number cannot be used together. So you cannot use the two pins labelled PWM_A[0] at the same time.