MicroPython Guide
Table of Contents
Standard Library Classes
MicroPython provides built-in classes for hardware control:
| Class | Purpose | Common Uses |
|---|---|---|
| Pin | Control digital GPIO pins | Button input, LED output, digital sensors |
| PWM | Pulse Width Modulation | LED dimming, motor speed control, servo control |
| ADC | Analog to Digital Converter | Read sensor voltages, potentiometers, analog input |
| DAC | Digital to Analog Converter | Generate analog signals (limited ESP32 support) |
| I2C | Inter-Integrated Circuit protocol | OLED displays, temperature sensors, accelerometers |
| SPI | Serial Peripheral Interface | TFT displays, SD cards, high-speed sensors |
| UART | Universal Asynchronous Receiver-Transmitter | GPS modules, GSM modules, serial communication |
| Timer | Hardware timer | Schedule repeated tasks, periodic interrupts |
| RTC | Real-Time Clock | Timekeeping, timestamps, alarms |
Quick Examples
from machine import Pin, PWM, ADC
# Digital output (LED)
led = Pin(25, Pin.OUT)
led.value(1) # Turn on
# PWM (LED dimming)
pwm_led = PWM(Pin(15))
pwm_led.freq(1000)
pwm_led.duty_u16(32768) # 50% brightness
# Analog input (sensor)
adc = ADC(Pin(26))
reading = adc.read_u16() # Read voltage
MicroPython Stubs
What Are Stubs?
Stub = A simplified placeholder that defines the structure without implementation.
Origin: Like a cigarette stub, pencil stub, or ticket stub - a small remaining portion that identifies the original.
In programming, MicroPython stubs are fake Python files that contain only class and function definitions (no actual hardware code). They help your IDE provide: - ✅ Auto-completion - ✅ Error checking - ✅ Type hints - ✅ IntelliSense
Why Are Stubs Needed?
Hardware-specific code (like machine.Pin) cannot run on your computer, so stubs provide the interface definitions for IDE support.
Stub Example:
# This is a stub file - not real code
class Pin:
def __init__(self, pin, mode):
# Actual hardware code would be here
pass
def value(self, val=None):
# Actual hardware code would be here
pass
Installing Stubs
1. Check MicroPython Version on Your Board
Connect to your microcontroller and run:
import sys
print(sys.implementation)
2. Install Matching Stub Package
# For Raspberry Pi Pico (RP2040)
pip install micropython-rp2-stubs==1.17.*
# For ESP32
pip install micropython-esp32-stubs==1.20.*
# For STM32
pip install micropython-stm32-stubs==1.19.*
Note: Replace version number (1.17, 1.20, etc.) with your board's MicroPython version.
Adding Stubs to Your Project
There are three methods:
Method 1: Virtual Environment (Recommended)
# Create virtual environment
python -m venv .venv
# Activate it
# Windows:
.venv\Scripts\activate
# Linux/Mac:
source .venv/bin/activate
# Install stubs
pip install micropython-rp2-stubs
VS Code will automatically detect stubs in the virtual environment.
Method 2: Project-Specific Settings
Create .vscode/settings.json in your project:
{
"python.analysis.extraPaths": [
"path/to/stubs"
]
}
Method 3: Global Settings
Add stub path to global VS Code settings (applies to all projects).
Stub Resources
- Stub Generator: micropython-stubber
- Pre-generated Stubs: micropython-stubs
UF2 Firmware Format
What is UF2?
UF2 = USB Flashing Format
A file format created by Microsoft for easy firmware flashing to microcontrollers.
How It Works
Traditional firmware flashing requires special software (like Rufus or Balena Etcher for OS installation). UF2 simplifies this to drag-and-drop.
Flashing Process
- Enter Bootloader Mode
- Hold the
BOOTSELbutton on your board - While holding, connect USB cable to computer
-
Board appears as USB mass storage device
-
Drag and Drop
- Copy the
.uf2file to the mounted drive - Board automatically reboots with new firmware
What's Included in UF2?
A complete package containing:
- MicroPython interpreter
- Board-specific libraries (e.g., rp2 for Raspberry Pi Pico)
- Hardware drivers
- Standard library modules
Download UF2 Files
Official firmware downloads: micropython.org/download
Popular Boards: - Raspberry Pi Pico / Pico W - ESP32 / ESP8266 - STM32 - PyBoard - BBC micro:bit
mpremote Tool
What is mpremote?
Official command-line tool from MicroPython for interacting with microcontrollers.
Installation
pip install mpremote
Basic Commands
Connect to Board
# Auto-connect and open REPL
mpremote
# Exit REPL: Ctrl+X or Ctrl+]
File Management
# List files on board
mpremote ls
# Copy file TO board
mpremote cp main.py :main.py
mpremote cp local_file.py :remote_file.py
# Copy file FROM board
mpremote cp :main.py main.py
mpremote cp :remote_file.py local_file.py
# Copy entire directory
mpremote cp -r src/ :src/
# Delete file
mpremote rm main.py
# Delete directory
mpremote rm -rf :old_project/
Run Code
# Run Python file without saving to board
mpremote run test.py
# Execute Python command directly
mpremote exec "print('Hello from Pico!')"
# Import and run saved module
mpremote exec "import main"
# Run and display output
mpremote run blink.py
Port Management
# List available serial ports
mpremote connect list
# Connect to specific port (Windows)
mpremote connect COM3 ls
# Connect to specific port (Linux/Mac)
mpremote connect /dev/ttyUSB0 ls
mpremote connect /dev/ttyACM0 ls
# Auto-detect and connect
mpremote connect auto ls
Advanced Usage
# Mount local directory on board (filesystem overlay)
mpremote mount .
# Reset the board
mpremote reset
# Enter raw REPL mode
mpremote repl --raw
# Run command then disconnect
mpremote exec "import machine; machine.reset()"
# Chain multiple commands
mpremote cp main.py :main.py + reset
Common Workflows
Deploy Project to Board
# Upload all Python files
mpremote cp main.py :main.py
mpremote cp utils.py :utils.py
mpremote cp config.py :config.py
# Or use mount for development
mpremote mount . exec "import main"
Quick Testing
# Test code without saving
mpremote run test_sensor.py
# Or execute directly
mpremote exec "
from machine import Pin
led = Pin(25, Pin.OUT)
led.value(1)
"
Debugging
# Connect and see print output
mpremote
# Or run with output
mpremote run debug.py
Troubleshooting
Board not detected:
# Check connections
mpremote connect list
# Try specific port
mpremote connect COM3 # Windows
mpremote connect /dev/ttyUSB0 # Linux
Permission denied (Linux):
# Add user to dialout group
sudo usermod -a -G dialout $USER
# Log out and back in
Soft reboot after changes:
mpremote exec "import machine; machine.soft_reset()"
Quick Reference
Essential Commands
| Task | Command |
|---|---|
| Connect to board | mpremote |
| List files | mpremote ls |
| Upload file | mpremote cp file.py :file.py |
| Download file | mpremote cp :file.py file.py |
| Delete file | mpremote rm file.py |
| Run without saving | mpremote run script.py |
| Execute Python | mpremote exec "print('hi')" |
| Reset board | mpremote reset |
| List ports | mpremote connect list |
Stub Installation
# Raspberry Pi Pico
pip install micropython-rp2-stubs
# ESP32
pip install micropython-esp32-stubs
# Check available stubs
pip search micropython-stubs
UF2 Flashing
- Hold
BOOTSELbutton - Connect USB cable
- Drag
.uf2file to drive - Done!
Additional Resources
- Official Documentation: docs.micropython.org
- MicroPython Downloads: micropython.org/download
- mpremote Documentation: docs.micropython.org/en/latest/reference/mpremote.html
- Stub Generator: github.com/Josverl/micropython-stubber
- Community Forum: forum.micropython.org
Tips & Best Practices
- Use virtual environments for stub management
- Match stub versions with your board's MicroPython version
- Use
mpremote mountduring development for instant testing - Always have a
main.pyfor auto-run on boot - Keep
boot.pyfor hardware initialization - Use
try-exceptblocks for robust embedded code - Test incrementally with
mpremote runbefore deploying
Happy MicroPython coding! 🐍🔌