MicroPython is a version of Python made to run on microcontrollers. If you already know a little Python, or want to learn, it's the friendliest way to start controlling real hardware. These examples use a Raspberry Pi Pico, Pico W, Pico 2 or Pico 2 W.
Getting set up
- Download the MicroPython firmware (a
.uf2file) for your exact board from the official MicroPython website. - Hold the BOOTSEL button on the Pico while plugging it into USB. It appears as a drive on your computer.
- Drag the
.uf2file onto that drive. The Pico restarts running MicroPython. - Install Thonny, a free beginner's editor. In its interpreter settings, choose MicroPython (Raspberry Pi Pico). You can now type code and run it on the board.
1. Blink the built-in LED
from machine import Pin
import time
led = Pin("LED", Pin.OUT) # the Pico's on-board LED
while True:
led.toggle() # switch on if off, off if on
time.sleep(0.5) # wait half a second
Pin controls the board's pins. Pin.OUT makes it an output, and "LED" is a name MicroPython gives the on-board LED on every Pico model. The while True loop runs for ever.
2. Read a button
Connect a push button between GP14 and any GND pin. No resistor is needed, because we'll switch on the Pico's built-in pull-up resistor.
from machine import Pin
import time
button = Pin(14, Pin.IN, Pin.PULL_UP)
led = Pin("LED", Pin.OUT)
while True:
pressed = button.value() == 0 # pull-up: reads 0 when pressed
led.value(pressed)
time.sleep(0.01)
With a pull-up, the pin reads 1 normally. Pressing the button connects it to ground, so it reads 0. This "active low" pattern is very common.
3. Fade an LED with PWM
Connect an LED and a 330 Ω resistor in series from GP15 to GND (longer leg towards GP15). See how LEDs work if that's new.
from machine import Pin, PWM
import time
pwm = PWM(Pin(15))
pwm.freq(1000) # switch 1,000 times a second
while True:
for duty in range(0, 65536, 1024): # brighten
pwm.duty_u16(duty)
time.sleep(0.01)
for duty in range(65535, -1, -1024): # dim
pwm.duty_u16(duty)
time.sleep(0.01)
PWM switches the pin on and off very fast. duty_u16 sets the share of time it's on, from 0 (always off) to 65,535 (always on). Your eye sees the average as brightness.
4. Read a potentiometer
A potentiometer (a knob) has three legs. Connect the outer two to 3V3 (OUT) and GND, and the middle one to GP26.
from machine import ADC, Pin
import time
pot = ADC(Pin(26))
while True:
raw = pot.read_u16() # 0 to 65,535
volts = raw * 3.3 / 65535
percent = raw * 100 / 65535
print("{:.2f} V ({:.0f}%)".format(volts, percent))
time.sleep(0.2)
Turn the knob and watch the numbers change in Thonny's shell. The Pico's analogue pins are GP26, GP27 and GP28, and they measure 0 to 3.3 V. To measure anything higher, like a battery, use a divider: see reading a battery voltage.
Where next
- Combine the examples: use the potentiometer to set the LED's brightness.
- Add a sensor, such as a temperature sensor or a distance sensor, using its MicroPython library.
- On a Pico W or Pico 2 W, connect to Wi-Fi and send readings to your phone.
Going deeper
Interrupts instead of polling
Checking a button in a loop works, but you can miss short presses and waste power. An interrupt runs a function the moment a pin changes:
from machine import Pin
import time
presses = 0
last = 0
def on_press(pin):
global presses, last
now = time.ticks_ms()
if time.ticks_diff(now, last) > 200: # ignore bounces within 200 ms
presses += 1
last = now
button = Pin(14, Pin.IN, Pin.PULL_UP)
button.irq(trigger=Pin.IRQ_FALLING, handler=on_press)
while True:
print("Presses:", presses)
time.sleep(1)
Keep interrupt handlers short: set a flag or count, and do the real work in the main loop. Mechanical buttons "bounce", making several contacts in a few milliseconds, which is why we ignore presses that come too close together.
Finding I²C devices
Most sensors and small displays use I²C, a two-wire bus. This lists the address of every device connected to GP4 (SDA) and GP5 (SCL):
from machine import I2C, Pin
i2c = I2C(0, sda=Pin(4), scl=Pin(5), freq=400_000)
print([hex(addr) for addr in i2c.scan()])
If nothing appears, check the wiring, the power, and that the bus has pull-up resistors (many sensor boards include them).
Doing several things at once
MicroPython includes asyncio, which lets one program juggle tasks, such as blinking an LED while reading a sensor, without complicated timing code. Each task runs until it reaches an await, then lets the others run.
Speed and memory
- MicroPython is much slower than C. For tight loops, the
@micropython.nativeand@micropython.viperdecorators compile functions to machine code for a large speed-up. - Memory is limited, so avoid building large strings or lists in loops. If you see memory errors, calling
gc.collect()at sensible points helps. - For timing-critical signals, use hardware features like PWM, PIO or timers, not Python loops.
Sources
The main references behind this guide. Numbers we worked out ourselves, such as the code outputs, come from running the code.