0
0
Iot-protocolsHow-ToBeginner · 4 min read

How to Program Raspberry Pi Pico with MicroPython Easily

To program the Raspberry Pi Pico with MicroPython, first install the MicroPython firmware using the Raspberry Pi Imager or download it from the official site. Then, use a code editor like Thonny to write and upload your Python scripts directly to the Pico via USB.
📐

Syntax

MicroPython on Raspberry Pi Pico uses Python syntax to control hardware pins and perform tasks. The basic structure includes importing modules, setting up pins, and writing logic.

  • import machine: Access hardware features like pins.
  • Pin(pin_number, mode): Define a pin as input or output.
  • pin.value(): Read or set the pin's state.
python
import machine

led = machine.Pin(25, machine.Pin.OUT)  # Set onboard LED as output
led.value(1)  # Turn LED on
led.value(0)  # Turn LED off
💻

Example

This example blinks the onboard LED on the Raspberry Pi Pico every second. It shows how to use the machine module and time module to control hardware and timing.

python
import machine
import time

led = machine.Pin(25, machine.Pin.OUT)  # Onboard LED

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 onboard LED blinks on and off every second continuously.
⚠️

Common Pitfalls

Some common mistakes when programming Raspberry Pi Pico with MicroPython include:

  • Not installing the MicroPython firmware before uploading code.
  • Using incorrect pin numbers or modes (input vs output).
  • Forgetting to save the script as main.py or boot.py to run automatically on boot.
  • Not resetting the Pico after flashing new code.
python
import machine

# Wrong: Using pin number 26 as output but missing mode argument
led = machine.Pin(26)  # Missing mode argument
led.value(1)  # This will cause an error

# Correct:
led = machine.Pin(26, machine.Pin.OUT)
led.value(1)
📊

Quick Reference

Here is a quick cheat sheet for common MicroPython commands on Raspberry Pi Pico:

CommandDescription
machine.Pin(pin, mode)Create a pin object with input/output mode
pin.value()Read pin state (0 or 1)
pin.value(x)Set pin state to 0 (off) or 1 (on)
time.sleep(seconds)Pause program for given seconds
import machineAccess hardware control functions
import timeAccess timing functions

Key Takeaways

Install MicroPython firmware on Raspberry Pi Pico before programming.
Use the machine.Pin class to control GPIO pins with input/output modes.
Write and upload scripts using editors like Thonny via USB connection.
Save scripts as main.py or boot.py to run automatically on startup.
Test simple examples like blinking the onboard LED to verify setup.