In this project, you’ll learn how to programme a Raspberry Pi Pico and PWM using MicroPython by connecting it to another computer.
A Raspberry Pi Pico is a microcontroller with a low price tag. Microcontrollers are little computers, but they lack huge amounts of storage and auxiliary devices to which they can be connected (for example, keyboards or monitors).
A Raspberry Pi Pico, like a Raspberry Pi computer, features GPIO pins, allowing it to control and receive input from a wide range of electronic devices.
Control LED brightness with PWM
Pulse width modulation, allows you to give analogue behaviours to digital devices, such as LEDs. This means that rather than an LED being simply on or off, you can control its brightness.
Parts required
- resistor between about 50 and 330 ohms
- an LED
- pair of M-M jumper
- Raspberry Pi Pico
Schematic diagram
Code
from machine import Pin, PWM from time import sleep pwm = PWM(Pin(15)) pwm.freq(1000) while True: for duty in range(65025): pwm.duty_u16(duty) sleep(0.0001) for duty in range(65025, 0, -1): pwm.duty_u16(duty) sleep(0.0001)
The frequency (PWM. freq) tells Raspberry Pi Pico how often to switch the power between on and off for the LED.
The duty cycle tells the LED for how long it should be on each time. For Raspberry Pi Pico in MicroPython, this can range from 0 to 65025. 65025 would be 100% of the time, so the LED would stay bright. A value of around 32512 would indicate that it should be on for half the time.