In this tutorial, we will see what modules are in MicroPython, how they work, how to create them, and how to use them to organize our code.
Basically, a module is a file containing Python code (in our case, MicroPython) that can be imported to use this code in another part of the program.
Modules allow us to organize code into separate files, which promotes reuse, maintenance, and keeps everything cleaner 😊.
How to Use Modules
Creating a Module
Creating a module in MicroPython is very simple. We just save our code in a file with a .py extension containing functions or variables.
For example, if we want to make a set of math-related functions, we can place them in a module called mathematics.py
# mathematics.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
Importing a Module
To use the functions of a module in another file, we need to import it into the program that needs it. We use the import keyword for this:
import mathematics
result_add = mathematics.add(10, 5)
result_subtract = mathematics.subtract(10, 5)
print(result_add) # Output: 15
print(result_subtract) # Output: 5
We can also import specific functions from a module:
from mathematics import add
result = add(7, 3)
print(result) # Output: 10
Standard MicroPython Modules
MicroPython includes a series of built-in modules specifically designed for working with hardware. Some of the most important ones are:
| Module | Description |
|---|---|
machine | Allows control of hardware, such as GPIO pins, I2C, SPI, and PWM. |
time | Provides functions for managing time and execution delays. |
utime | Similar to time, but optimized for MicroPython. |
sys | Offers information about the system and script execution. |
os | Allows interaction with the file system. |
gc | Provides control over the garbage collector. |
network | Allows management of network connections, such as WiFi and sockets. |
ujson | Handles encoding and decoding of data in JSON format. |
ure | Provides regular expressions in MicroPython. |
ustruct | Allows efficient manipulation of binary data. |
ubinascii | Offers functions for conversion between binary and ASCII data (Base64, hex, etc.). |
random | Pseudo-random number generation. |
math | Mathematical functions like sines, cosines, square root, etc. |
builtins | Contains Python’s built-in functions and exceptions. |
To use them, we simply do an import and we have the available functionalities in our code.
import machine
led = machine.Pin(2, machine.Pin.OUT) # Configures pin 2 as an output
led.value(1) # Turns on the LED
You can list the modules available on your board by running
help(“modules”)
Third-Party Modules
Sometimes we will need to install modules developed by the community. That is, what we normally call “libraries” (which in MicroPython will be modules).
In the next tutorial, we will see how to download and use libraries developed by third parties in our projects.
