Micropython is a lightweight implementation of Python 3 optimized to run on microcontrollers and embedded systems with limited resources.
Introduction
Install Micropython on a device
Flash the Micropython firmware onto a device (like the ESP32 or ESP8266) using tools like esptool.py
:
esptool.py --chip esp32 --port /dev/ttyUSB0 write_flash -z 0x1000 firmware.bin
Verify the installation
Connect the microcontroller to your PC and use a serial terminal like PuTTY or Minicom to verify the installation.
screen /dev/ttyUSB0 115200
Read the version
To check the installed version of MicroPython.
import sys
print(sys.version)
Basic commands in REPL
Start REPL
Once connected, start the interactive REPL (Read Eval Print Loop) terminal with the following line:
screen /dev/ttyUSB0 115200
Exit REPL
To exit the REPL, press Ctrl+A
, followed by Ctrl+D
.
Execute a command
You can run commands directly:
>>> print("Hello, Micropython")
Run a script
To run a script in MicroPython, you first need to upload it to the device, and then use the following command in the REPL (Read-Eval-Print Loop).
import main
File management
List files in the system
View the files stored on the microcontroller.
import os
os.listdir()
Upload a file to Micropython
You can use ampy
to upload files from your computer.
ampy --port /dev/ttyUSB0 put my_script.py
Create a file
Create a file and write content to it.
with open('file.txt', 'w') as f:
f.write('Hello, MicroPython!')
Read a file
Read the content of a file.
with open('file.txt', 'r') as f:
print(f.read())
Delete a file
Delete a specific file:
os.remove('my_script.py')
Hardware control
GPIO (Input/Output)
Digital outputs
To configure an output pin, such as turning on an LED on pin 2:
from machine import Pin
led = Pin(2, Pin.OUT)
led.value(1) # Turn on
led.value(0) # Turn off
Digital inputs
Configure a pin as input, for example, to read the state of a button.
button = Pin(4, Pin.IN, Pin.PULL_UP)
button_state = button.value() # Read button value
Generate a PWM signal
Use PWM (Pulse Width Modulation) to control devices like motors or the brightness of an LED.
from machine import Pin, PWM
pwm = PWM(Pin(15))
pwm.freq(500) # Frequency of 500Hz
pwm.duty(512) # 50% duty cycle
Peripherals
UART (Serial communication)
Initialize UART communication
Set up a UART port for serial communication.
from machine import UART
uart = UART(1, baudrate=9600, tx=17, rx=16)
uart.write('Hello, UART!')
Read data from UART
data = uart.read(10) # Read up to 10 bytes
I2C
Initialize I2C communication
Set up I2C pins and communicate with sensors or displays.
from machine import I2C, Pin
i2c = I2C(scl=Pin(22), sda=Pin(21))
devices = i2c.scan() # Search for connected devices
Read and write to an I2C device
Read from an I2C device:
data = i2c.readfrom(0x3C, 2) # Read 2 bytes from the device with address 0x3C
Write data:
i2c.writeto(0x3C, b'\x01\x02') # Send 2 bytes
Data manipulation
Type conversion
You can convert between data types, such as integers and strings.
number = int("123") # String to integer
text = str(123) # Integer to string
String formatting
Use Python’s string formatting to print data in a custom way.
age = 21
print("I am {} years old".format(age))
Working with lists
Micropython supports list operations, just like in Python.
my_list = [1, 2, 3]
my_list.append(4) # Add an element
my_list.remove(2) # Remove an element
Internet connection
Connect to Wi-Fi
Connect to a Wi-Fi network.
import network
ssid = 'your_ssid'
password = 'your_password'
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, password)
while not wlan.isconnected():
pass
print('Connected to', ssid)
print('IP Address:', wlan.ifconfig()[0])
Send data to an HTTP server
Send a GET request to a server.
import urequests
response = urequests.get('http://your-api.com/data')
print(response.text)
Debugging
Print to console
Use print
to debug and see values at runtime.
print("The value of the LED is:", led.value())
Exception handling
Basic exception handling.
try:
# Code that may raise an exception
value = 10 / 0
except ZeroDivisionError:
print("Error: Division by zero")
Check available memory
Use gc
to check available memory and clean up accumulated garbage.
import gc
gc.collect() # Force garbage collection
free_memory = gc.mem_free() # Check available memory