MicroPython Commands Reference¶
A quick reference guide for commonly used MicroPython commands, especially for RP2040 boards like the XIAO RP2040.
REPL (Interactive Shell) Commands¶
Basic REPL Control¶
# Soft reboot (Ctrl+D in REPL)
import machine
machine.soft_reset()
# Hard reset
machine.reset()
# Exit REPL back to terminal (Ctrl+X)
# (This is a keyboard command, not Python)
Help System¶
help() # General help
help(machine) # Help on a module
dir() # List available modules/objects
dir(machine) # List contents of a module
File System Operations¶
Listing Files¶
import os
os.listdir() # List files in current directory
os.listdir('/') # List files in root
os.getcwd() # Get current working directory
File Operations¶
# Create/write a file
with open('data.txt', 'w') as f:
f.write('Hello World\n')
# Read a file
with open('data.txt', 'r') as f:
content = f.read()
print(content)
# Append to a file
with open('data.txt', 'a') as f:
f.write('More data\n')
# Delete a file
os.remove('data.txt')
# Rename a file
os.rename('old.txt', 'new.txt')
# Create directory
os.mkdir('data')
# Remove directory
os.rmdir('data')
# Check if file exists
try:
os.stat('file.txt')
print("File exists")
except OSError:
print("File not found")
GPIO (Digital I/O)¶
Pin Setup¶
from machine import Pin
# Output pin
led = Pin(25, Pin.OUT) # Pin 25 as output (onboard LED on some boards)
# Input pin
button = Pin(14, Pin.IN, Pin.PULL_UP) # Pin 14 with internal pull-up
# Input without pull resistor
sensor = Pin(15, Pin.IN)
Digital Write/Read¶
# Write digital output
led.value(1) # Set HIGH (3.3V)
led.value(0) # Set LOW (0V)
led.on() # Alternative: turn on
led.off() # Alternative: turn off
led.toggle() # Toggle state
# Read digital input
state = button.value() # Returns 1 or 0
Pin Interrupts¶
from machine import Pin
def button_callback(pin):
print("Button pressed!")
button = Pin(14, Pin.IN, Pin.PULL_UP)
button.irq(trigger=Pin.IRQ_FALLING, handler=button_callback)
# Triggers: Pin.IRQ_RISING, Pin.IRQ_FALLING, Pin.IRQ_RISING | Pin.IRQ_FALLING
PWM (Pulse Width Modulation)¶
Basic PWM¶
from machine import Pin, PWM
# Create PWM on pin
pwm = PWM(Pin(16))
# Set frequency (Hz)
pwm.freq(1000) # 1 kHz
# Set duty cycle (0-65535)
pwm.duty_u16(32768) # 50% duty cycle
pwm.duty_u16(65535) # 100% (fully on)
pwm.duty_u16(0) # 0% (fully off)
# Turn off PWM
pwm.deinit()
LED Fading Example¶
from machine import Pin, PWM
import time
led = PWM(Pin(25))
led.freq(1000)
# Fade in
for duty in range(0, 65536, 256):
led.duty_u16(duty)
time.sleep_ms(10)
# Fade out
for duty in range(65535, -1, -256):
led.duty_u16(duty)
time.sleep_ms(10)
ADC (Analog to Digital Converter)¶
Reading Analog Values¶
from machine import ADC, Pin
# Create ADC object (RP2040 has ADC on pins 26-29)
adc = ADC(Pin(26))
# Read raw value (0-65535 for 16-bit)
raw_value = adc.read_u16()
# Convert to voltage (0-3.3V)
voltage = raw_value * 3.3 / 65535
print(f"Raw: {raw_value}, Voltage: {voltage:.2f}V")
Temperature Sensor (RP2040 Internal)¶
from machine import ADC
import time
sensor_temp = ADC(4) # Internal temperature sensor
conversion_factor = 3.3 / 65535
while True:
reading = sensor_temp.read_u16() * conversion_factor
temperature = 27 - (reading - 0.706) / 0.001721
print(f"Temperature: {temperature:.1f}°C")
time.sleep(1)
Timers and Delays¶
Basic Delays¶
import time
time.sleep(1) # Sleep for 1 second
time.sleep_ms(500) # Sleep for 500 milliseconds
time.sleep_us(1000) # Sleep for 1000 microseconds
# Get current time (milliseconds since boot)
start = time.ticks_ms()
# ... do something ...
elapsed = time.ticks_diff(time.ticks_ms(), start)
print(f"Elapsed: {elapsed}ms")
Hardware Timers¶
from machine import Timer
# Callback function
def timer_callback(timer):
print("Timer fired!")
led.toggle()
# Create timer (RP2040 has multiple timers)
timer = Timer()
# Initialize periodic timer (1 Hz = every 1000ms)
timer.init(freq=1, mode=Timer.PERIODIC, callback=timer_callback)
# Or use period in milliseconds
timer.init(period=1000, mode=Timer.PERIODIC, callback=timer_callback)
# One-shot timer
timer.init(period=5000, mode=Timer.ONE_SHOT, callback=timer_callback)
# Stop timer
timer.deinit()
UART (Serial Communication)¶
Basic UART Setup¶
from machine import UART, Pin
# UART0: TX=Pin(0), RX=Pin(1)
# UART1: TX=Pin(4), RX=Pin(5) or TX=Pin(8), RX=Pin(9)
uart = UART(0, baudrate=9600, tx=Pin(0), rx=Pin(1))
# Send data
uart.write('Hello\n')
uart.write(b'Binary data\n')
# Read data
if uart.any(): # Check if data available
data = uart.read() # Read all available
print(data)
# Read specific number of bytes
data = uart.read(10) # Read 10 bytes
# Read line
line = uart.readline() # Read until newline
I2C (Inter-Integrated Circuit)¶
I2C Setup¶
from machine import I2C, Pin
# I2C0: SDA=Pin(4), SCL=Pin(5)
# I2C1: SDA=Pin(6), SCL=Pin(7)
i2c = I2C(0, scl=Pin(5), sda=Pin(4), freq=400000)
# Scan for devices
devices = i2c.scan()
print("I2C devices found:", [hex(device) for device in devices])
# Write to device
i2c.writeto(0x3C, b'\x00\x01')
# Read from device
data = i2c.readfrom(0x3C, 2) # Read 2 bytes from address 0x3C
# Write then read (common pattern)
i2c.writeto_mem(0x3C, 0x00, b'\x01') # Write to register
data = i2c.readfrom_mem(0x3C, 0x00, 1) # Read from register
SPI (Serial Peripheral Interface)¶
SPI Setup¶
from machine import SPI, Pin
# SPI0: SCK=Pin(2), MOSI=Pin(3), MISO=Pin(4)
# SPI1: SCK=Pin(10), MOSI=Pin(11), MISO=Pin(12)
spi = SPI(0, baudrate=1000000, polarity=0, phase=0,
sck=Pin(2), mosi=Pin(3), miso=Pin(4))
cs = Pin(5, Pin.OUT) # Chip select
# Write data
cs.value(0)
spi.write(b'\x01\x02\x03')
cs.value(1)
# Read data
cs.value(0)
data = spi.read(4) # Read 4 bytes
cs.value(1)
# Write and read simultaneously
cs.value(0)
result = spi.write_readinto(b'\xFF\xFF', buffer)
cs.value(1)
WiFi (If using Pico W or WiFi-enabled board)¶
Connecting to WiFi¶
import network
import time
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect('SSID', 'PASSWORD')
# Wait for connection
max_wait = 10
while max_wait > 0:
if wlan.status() < 0 or wlan.status() >= 3:
break
max_wait -= 1
print('Waiting for connection...')
time.sleep(1)
# Check status
if wlan.status() != 3:
raise RuntimeError('Network connection failed')
else:
print('Connected')
status = wlan.ifconfig()
print('IP:', status[0])
# Disconnect
wlan.disconnect()
wlan.active(False)
JSON Data Handling¶
Reading/Writing JSON¶
import json
# Write JSON to file
data = {
'sensor': 'DHT22',
'temperature': 23.5,
'humidity': 65.2
}
with open('config.json', 'w') as f:
json.dump(data, f)
# Read JSON from file
with open('config.json', 'r') as f:
config = json.load(f)
print(config['temperature'])
# Convert to/from JSON strings
json_string = json.dumps(data)
parsed_data = json.loads(json_string)
WatchDog Timer (System Reliability)¶
Watchdog Setup¶
from machine import WDT
# Create watchdog with 5 second timeout
wdt = WDT(timeout=5000) # milliseconds
# In your main loop, feed the watchdog
while True:
wdt.feed() # Reset watchdog timer
# ... your code ...
time.sleep(1)
# If wdt.feed() isn't called within 5 seconds, board resets
Memory and System Info¶
System Information¶
import gc
import micropython
import sys
# Garbage collection
gc.collect() # Run garbage collector
print("Free memory:", gc.mem_free())
print("Used memory:", gc.mem_alloc())
# Memory info
micropython.mem_info()
# System info
print("Platform:", sys.platform)
print("Version:", sys.version)
print("Implementation:", sys.implementation)
# Flash size
import os
stat = os.statvfs('/')
block_size = stat[0]
total_blocks = stat[2]
free_blocks = stat[3]
print(f"Flash: {total_blocks * block_size / 1024 / 1024:.2f} MB")
print(f"Free: {free_blocks * block_size / 1024 / 1024:.2f} MB")
Common Patterns¶
Blinking LED¶
from machine import Pin
import time
led = Pin(25, Pin.OUT)
while True:
led.toggle()
time.sleep(0.5)
Button with Debouncing¶
from machine import Pin
import time
button = Pin(14, Pin.IN, Pin.PULL_UP)
last_state = 1
debounce_time = 50 # milliseconds
while True:
current_state = button.value()
if current_state != last_state:
time.sleep_ms(debounce_time)
if button.value() == current_state:
if current_state == 0:
print("Button pressed!")
last_state = current_state
Non-blocking Blink (Using millis pattern)¶
from machine import Pin
import time
led = Pin(25, Pin.OUT)
led_state = False
last_toggle = time.ticks_ms()
interval = 1000 # milliseconds
while True:
current = time.ticks_ms()
if time.ticks_diff(current, last_toggle) >= interval:
led_state = not led_state
led.value(led_state)
last_toggle = current
# Other code can run here without blocking
mpremote Commands (From Computer Terminal)¶
Basic mpremote¶
# Connect and get REPL
mpremote connect auto repl
# Run a command
mpremote connect auto exec "print('Hello')"
# Copy file to board
mpremote connect auto fs cp main.py :
# Copy file from board
mpremote connect auto fs cp :main.py ./main.py
# List files on board
mpremote connect auto fs ls
# Remove file from board
mpremote connect auto fs rm main.py
# Make directory
mpremote connect auto fs mkdir data
# Chain commands
mpremote connect auto fs cp main.py : + reset
# Run a local script on the board
mpremote connect auto run test.py
Troubleshooting Commands¶
Common Debug Steps¶
# Check what's running on startup
import os
print(os.listdir())
# Test if main.py exists
try:
with open('main.py', 'r') as f:
print(f.read())
except:
print("main.py not found")
# Safe mode - rename main.py temporarily
os.rename('main.py', 'main.py.bak')
# Restore
os.rename('main.py.bak', 'main.py')
# Check for exceptions
import sys
sys.print_exception(e) # Print exception details
Quick Reference: XIAO RP2040 Pinout¶
Pin Mapping:
- GPIO 0-29 available
- ADC: GPIO 26, 27, 28, 29 (ADC 0-3)
- I2C0: SDA=GP4, SCL=GP5
- I2C1: SDA=GP6, SCL=GP7
- SPI0: SCK=GP2, MOSI=GP3, MISO=GP4
- UART0: TX=GP0, RX=GP1
- Built-in LED: GPIO 25 (varies by board)
- User button: BOOT button for BOOTSEL
Tips¶
- Always use
gc.collect()after large operations to free memory - Use
try/exceptblocks to handle errors gracefully - Feed the watchdog in long-running loops for reliability
- Use
time.ticks_ms()for non-blocking timing - Store configs in JSON files for easy modification
- Test interactively in REPL before writing to main.py
This reference is optimized for RP2040-based boards like the XIAO RP2040. Some features may vary on other MicroPython boards.