MicroPython basics
What you’ll learn
- What MicroPython is and which boards run it
- Python syntax compared with Arduino C++
- Controlling pins, reading inputs and timing
MicroPython
MicroPython is a small version of Python that runs directly on microcontrollers such as the Raspberry Pi Pico, ESP32 and BBC micro:bit. You type code, save it as main.py on the board, and it runs.
Python vs Arduino C++
| Arduino C++ | MicroPython |
|---|---|
int x = 5; |
x = 5 |
{ } blocks |
indentation (4 spaces) |
; at line ends |
no semicolons |
if (x > 3) { ... } |
if x > 3: |
for (int i = 0; i < 5; i++) |
for i in range(5): |
delay(500) |
time.sleep(0.5) |
void loop() |
while True: |
Pins
from machine import Pin, ADCimport time
led = Pin(25, Pin.OUT) # outputbutton = Pin(14, Pin.IN, Pin.PULL_UP)knob = ADC(26) # analog input on the Pico
while True: if button.value() == 0: # pressed (pulled up) led.on() else: led.off() print(knob.read_u16()) # 0–65535 time.sleep(0.1)Example: a PWM fade on the Pico
from machine import Pin, PWMimport time
led = PWM(Pin(25))led.freq(1000)while True: for duty in range(0, 65536, 1024): led.duty_u16(duty) time.sleep(0.01)Example: the same blink in both languages
// Arduino C++void loop() { digitalWrite(13, HIGH); delay(500); digitalWrite(13, LOW); delay(500);}# MicroPythonwhile True: led.toggle() time.sleep(0.5)Try it in a virtual Raspberry Pi Pico
Press Start simulator, paste this into main.py, and press ▶. The LED on the Pico blinks and the console prints a count.
from machine import Pinimport time
led = Pin(25, Pin.OUT) # the Pico's on-board LED
for i in range(10): led.toggle() print("blink", i) time.sleep(0.5)Runs on Wokwi, free, no account needed.
Forever blinkEasy
Change the program to blink forever, twice per second.
Show an answer
while True: led.toggle() time.sleep(0.25)CountdownMedium
Print 10 down to 1, one per second, then “Go!”.
Show an answer
for n in range(10, 0, -1): print(n) time.sleep(1)print("Go!")Translate itHard
Translate the Arduino “count button presses” example (Arduino C++ basics lesson, Examples tab) into MicroPython.
Show an answer
from machine import Pinimport time
button = Pin(14, Pin.IN, Pin.PULL_UP)presses = 0was = Falsewhile True: pressed = button.value() == 0 if pressed and not was: presses += 1 print("Presses:", presses) time.sleep(0.05) was = pressedQuick check
Finished this lesson?