Introduction to MicroPython
MicroPython is a lean implementation of Python 3 designed to run on microcontrollers and embedded systems. It includes a subset of the Python standard library and is optimized to run on hardware with limited resources.
Key Features
- Python 3 syntax and semantics
- Interactive REPL (Read-Eval-Print Loop)
- Modules for hardware control (machine, network, time)
- Small memory footprint (< 256KB)
- Easy to learn for beginners
Variables and Data Types
Basic Variables
# Numbers
age = 25
temperature = 23.5
# Strings
name = "ESP32"
message = 'Hello MicroPython'
# Booleans
is_on = True
is_connected = False
# Print variables
print(name)
print("Temperature:", temperature)
Data Types
- int: Integer numbers (1, 42, -10)
- float: Decimal numbers (3.14, -0.5)
- str: Text strings ("hello")
- bool: True or False
- list: Ordered collection [1, 2, 3]
- tuple: Immutable collection (1, 2, 3)
- dict: Key-value pairs {"key": "value"}
Lists
# Create a list
sensors = ["DHT22", "BME280", "DS18B20"]
# Access elements
print(sensors[0]) # DHT22
print(sensors[-1]) # DS18B20
# Add elements
sensors.append("HC-SR04")
# Loop through list
for sensor in sensors:
print(sensor)
Dictionaries
# Create dictionary
sensor_data = {
"temperature": 25.5,
"humidity": 60,
"pressure": 1013
}
# Access values
print(sensor_data["temperature"])
# Add new key-value pair
sensor_data["altitude"] = 120
# Loop through dictionary
for key, value in sensor_data.items():
print(key, ":", value)
Control Flow
If Statements
temperature = 28
if temperature > 30:
print("Hot")
elif temperature > 20:
print("Comfortable")
else:
print("Cold")
# One-line if
status = "on" if temperature > 25 else "off"
For Loops
# Loop through range
for i in range(5):
print(i) # 0, 1, 2, 3, 4
# Loop through list
pins = [2, 4, 5, 18, 19]
for pin in pins:
print("Pin:", pin)
# Loop with index
for index, value in enumerate(pins):
print(f"Index {index}: Pin {value}")
While Loops
# Basic while loop
count = 0
while count < 5:
print(count)
count += 1
# While with break
while True:
value = read_sensor()
if value > 100:
break
time.sleep(1)
Functions
Basic Functions
# Simple function
def greet():
print("Hello from ESP32!")
greet()
# Function with parameters
def add(a, b):
return a + b
result = add(5, 3)
print(result) # 8
Default Parameters
def blink_led(pin, times=3, delay=0.5):
from machine import Pin
import time
led = Pin(pin, Pin.OUT)
for _ in range(times):
led.on()
time.sleep(delay)
led.off()
time.sleep(delay)
# Call with defaults
blink_led(2)
# Call with custom values
blink_led(2, times=5, delay=0.2)
Return Values
def read_temperature():
# Simulate reading
return 25.5
def get_sensor_data():
temp = 25.5
humidity = 60
return temp, humidity # Return multiple values
# Use returned values
temperature = read_temperature()
print(f"Temperature: {temperature}°C")
t, h = get_sensor_data()
print(f"Temp: {t}°C, Humidity: {h}%")
Working with Modules
Import Statements
# Import entire module
import time
time.sleep(1)
# Import specific functions
from time import sleep, sleep_ms
sleep(1)
# Import with alias
import machine as m
pin = m.Pin(2, m.Pin.OUT)
Essential MicroPython Modules
# machine - Hardware access
from machine import Pin, ADC, PWM, I2C, SPI
# time - Delays and timing
import time
time.sleep(1) # 1 second
time.sleep_ms(500) # 500 milliseconds
# network - Wi-Fi connectivity
import network
wlan = network.WLAN(network.STA_IF)
# os - File system operations
import os
os.listdir()
# json - JSON encoding/decoding
import json
data = json.dumps({"temp": 25.5})
Basic Hardware Control
GPIO Control
from machine import Pin
import time
# Setup LED on GPIO 2
led = Pin(2, Pin.OUT)
# Turn on/off
led.on()
time.sleep(1)
led.off()
# Toggle
led.value(not led.value())
# Setup button with pull-up
button = Pin(0, Pin.IN, Pin.PULL_UP)
if button.value() == 0:
print("Button pressed")
PWM (Pulse Width Modulation)
from machine import Pin, PWM
# Setup PWM on GPIO 2
led = PWM(Pin(2))
led.freq(1000) # 1kHz frequency
# Fade LED
for duty in range(0, 1024, 10):
led.duty(duty)
time.sleep_ms(10)
Analog Reading
from machine import ADC, Pin
# Setup ADC on GPIO 34
adc = ADC(Pin(34))
adc.atten(ADC.ATTN_11DB) # 0-3.3V range
# Read value
value = adc.read() # 0-4095
voltage = (value / 4095) * 3.3
print(f"Value: {value}, Voltage: {voltage:.2f}V")
Exception Handling
Try-Except Blocks
# Basic exception handling
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
# Multiple exceptions
try:
value = int("abc")
except ValueError:
print("Invalid number")
except Exception as e:
print(f"Error: {e}")
# Finally block
try:
file = open("data.txt")
content = file.read()
except OSError:
print("File not found")
finally:
file.close() # Always executes
Best Practices
Code Organization
- Use meaningful variable names
- Add comments to explain complex logic
- Break code into functions
- Keep functions small and focused
- Use constants for pin numbers and settings
Example: Well-Organized Code
# Constants
LED_PIN = 2
BUTTON_PIN = 0
BLINK_DELAY = 0.5
# Imports
from machine import Pin
import time
# Setup hardware
def setup():
led = Pin(LED_PIN, Pin.OUT)
button = Pin(BUTTON_PIN, Pin.IN, Pin.PULL_UP)
return led, button
# Main logic
def blink_led(led, times):
"""Blink LED specified number of times"""
for _ in range(times):
led.on()
time.sleep(BLINK_DELAY)
led.off()
time.sleep(BLINK_DELAY)
# Main program
def main():
led, button = setup()
print("Press button to blink LED")
while True:
if button.value() == 0: # Button pressed
blink_led(led, 3)
time.sleep(0.1)
# Run
if __name__ == "__main__":
main()
Practice Exercises
Exercise 1: Temperature Converter
Create a function that converts Celsius to Fahrenheit:
def celsius_to_fahrenheit(celsius):
# Your code here
pass
# Test
print(celsius_to_fahrenheit(25)) # Should print 77.0
Exercise 2: LED Patterns
Create a function that blinks LED in different patterns:
def led_pattern(led, pattern):
"""
pattern: list of (on_time, off_time) tuples
Example: [(0.1, 0.1), (0.5, 0.5), (0.1, 0.1)]
"""
# Your code here
pass
Exercise 3: Sensor Data Logger
Create a program that reads sensor data and stores it in a list:
def log_sensor_data(samples=10, delay=1):
"""
Read sensor data and return list of readings
"""
# Your code here
pass
Next Steps
Now that you understand MicroPython basics, explore these topics: