0
0
Iot-protocolsHow-ToBeginner · 3 min read

How to Program Raspberry Pi Pico with MicroPython Easily

To program the Raspberry Pi Pico with MicroPython, first install the MicroPython firmware on the Pico by copying the UF2 file while holding the BOOTSEL button. Then use a serial terminal or an IDE like Thonny to write and upload MicroPython scripts directly to the device.
📐

Syntax

MicroPython on the Pico uses Python-like syntax to control hardware pins and run code. You write scripts using import to load modules, Pin to control GPIO pins, and time.sleep() to pause execution.

Example parts:

  • import machine: Access hardware functions.
  • Pin(25, Pin.OUT): Set pin 25 as output (built-in LED).
  • pin.value(1): Turn pin on.
  • time.sleep(1): Wait 1 second.
python
import machine
import time

led = machine.Pin(25, machine.Pin.OUT)  # Built-in LED
led.value(1)  # Turn LED on

# Wait for 1 second
time.sleep(1)

led.value(0)  # Turn LED off
💻

Example

This example blinks the built-in LED on the Raspberry Pi Pico every second. It shows how to control pins and use delays in MicroPython.

python
import machine
import time

led = machine.Pin(25, machine.Pin.OUT)

while True:
    led.value(1)  # LED on
    time.sleep(1)  # Wait 1 second
    led.value(0)  # LED off
    time.sleep(1)  # Wait 1 second
Output
The built-in LED on the Pico blinks on and off every second continuously.
⚠️

Common Pitfalls

Common mistakes when programming Pico with MicroPython include:

  • Not holding the BOOTSEL button while plugging in to enter USB storage mode for flashing firmware.
  • Using incorrect pin numbers or modes (input vs output).
  • Forgetting to save scripts as main.py or boot.py to run automatically on boot.
  • Not installing or using an IDE like Thonny, which simplifies uploading and running code.
python
## Wrong: Using pin number that does not exist
import machine
led = machine.Pin(30, machine.Pin.OUT)  # Pico has pins 0-29 only

## Right:
led = machine.Pin(25, machine.Pin.OUT)  # Correct built-in LED pin
📊

Quick Reference

CommandDescription
Hold BOOTSEL + plug in USBEnter USB storage mode to flash MicroPython firmware
Copy UF2 firmware fileInstall MicroPython on Pico
Use Thonny IDEWrite, upload, and run MicroPython scripts easily
import machineAccess hardware functions
Pin(25, Pin.OUT)Set pin 25 as output (built-in LED)
pin.value(1)Turn pin on
time.sleep(seconds)Pause execution for given seconds

Key Takeaways

Hold the BOOTSEL button while plugging in to flash MicroPython firmware on the Pico.
Use the built-in LED on pin 25 to test your MicroPython code easily.
Write scripts in an IDE like Thonny for simple code upload and debugging.
Remember to save your main script as main.py to run automatically on boot.
Check pin numbers and modes carefully to avoid hardware errors.