MicroPython — Essential Patterns💻 Code
Most-used MicroPython patterns: timers, interrupts, file I/O and deep sleep.
⚡ Save as main.py on the device to run automatically on boot. boot.py runs first.
Most-used MicroPython patterns: timers, interrupts, file I/O and deep sleep.
from machine import Pin, Timer, deepsleep
import ujson, time
# Non-blocking timer (callback every 500 ms)
led = Pin(25, Pin.OUT)
tim = Timer()
tim.init(freq=2, mode=Timer.PERIODIC, callback=lambda t: led.toggle())
# Interrupt on button press
btn = Pin(14, Pin.IN, Pin.PULL_UP)
def on_press(pin):
print('Pressed!')
btn.irq(trigger=Pin.IRQ_FALLING, handler=on_press)
# File I/O
with open('data.txt', 'w') as f:
f.write('Hello\n')
with open('data.txt', 'a') as f:
f.write('World\n')
with open('data.txt') as f:
print(f.read())
# JSON config
config = {'ssid': 'MyWiFi', 'threshold': 25.0}
with open('config.json', 'w') as f:
ujson.dump(config, f)
with open('config.json') as f:
cfg = ujson.load(f)
# Deep sleep for 10 seconds (very low power)
deepsleep(10000) # milliseconds -- device restarts on wakeCircuitPython — Getting Started💻 Code
Adafruit's CircuitPython: code saves trigger automatic restart, excellent library ecosystem.
⚡ The CIRCUITPY drive appears as a USB drive. Edit code.py directly. Works on Pico, ESP32-S2/S3, and many Adafruit boards.
Adafruit's CircuitPython: code saves trigger automatic restart, excellent library ecosystem.
# code.py -- runs automatically on boot
import board, digitalio, analogio, time
# LED
led = digitalio.DigitalInOut(board.LED)
led.direction = digitalio.Direction.OUTPUT
# Button with pull-up
btn = digitalio.DigitalInOut(board.GP14)
btn.direction = digitalio.Direction.INPUT
btn.pull = digitalio.Pull.UP
# Analogue input
adc = analogio.AnalogIn(board.GP26)
while True:
led.value = not btn.value # Mirror button state
volts = adc.value * 3.3 / 65535
print(f'Button: {btn.value} ADC: {volts:.3f} V')
time.sleep(0.1)
# Install libraries:
# Option 1: copy .mpy files to /lib/ on CIRCUITPY drive
# Option 2: use circup (pip install circup)
# circup install adafruit_ssd1306
# circup install adafruit_dht
# circup install neopixelArduino — Non-Blocking Patterns💻 Code
Essential Arduino C++ patterns for timing without delay() and clean code structure.
⚡ Using delay() blocks everything else. Use millis() for non-blocking timing in any real project.
Essential Arduino C++ patterns for timing without delay() and clean code structure.
// Non-blocking blink using millis()
const int LED = 13;
unsigned long lastToggle = 0;
const long INTERVAL = 500; // ms
bool ledState = false;
void setup() {
pinMode(LED, OUTPUT);
Serial.begin(115200);
}
void loop() {
unsigned long now = millis();
if (now - lastToggle >= INTERVAL) {
lastToggle = now;
ledState = !ledState;
digitalWrite(LED, ledState);
}
// Other code here -- runs without blocking
}
// Running average (smoothed ADC reads)
const int SAMPLES = 10;
int readings[SAMPLES] = {0};
int idx = 0;
long total = 0;
int smoothRead(int pin) {
total -= readings[idx];
readings[idx] = analogRead(pin);
total += readings[idx];
idx = (idx + 1) % SAMPLES;
return total / SAMPLES;
}
// Non-blocking state machine example
enum State { IDLE, RUNNING, DONE };
State state = IDLE;
void loop() {
switch (state) {
case IDLE: /* wait for trigger */ break;
case RUNNING: /* do work */ break;
case DONE: state = IDLE; break;
}
}Package Management Reference⌨ Command
Install libraries for MicroPython, CircuitPython and Arduino.
Install libraries for MicroPython, CircuitPython and Arduino.
# MicroPython -- mip (requires WiFi)
import mip
mip.install('umqtt.simple')
mip.install('ssd1306')
mip.install('bme280')
# mpremote -- manage Pico from PC
pip install mpremote
mpremote connect /dev/ttyACM0 # connect
mpremote cp myfile.py : # copy to root
mpremote cp myfile.py :/lib/ # copy to lib
mpremote run myfile.py # run without saving
mpremote mip install bme280 # install package
mpremote ls # list files on device
# circup -- CircuitPython
pip install circup
circup install adafruit_ssd1306
circup install neopixel
circup update # update all
# Arduino CLI
arduino-cli lib install 'Adafruit BME280 Library'
arduino-cli lib install 'ArduinoJson'
arduino-cli lib list # installed librariesNo entries match