modulos-en-micropython

What are modules in MicroPython and how to use them

  • 3 min

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 that contains Python code (in our case MicroPython) that can be imported to use this code at another point in the program.

Modules allow us to organize code into separate files, which promotes reuse, maintenance, and keeps everything tidier 😊.

How to use modules

Creating a module

Creating a module in MicroPython is very simple. Just save your code in a file with a .py extension that contains functions or variables.

For example, if we want to create a set of functions related to mathematics, 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 in the program that needs it. We use the keyword import 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 set of built-in modules specifically designed to work with hardware. Some of the most important ones are:

ModuleDescription
machineAllows control of hardware, such as GPIO pins, I2C, SPI, and PWM.
timeProvides functions for managing time and delays in execution.
utimeSimilar to time, but optimized for MicroPython.
sysOffers information about the system and script execution.
osAllows interaction with the file system.
gcProvides control over the garbage collector.
networkAllows management of network connections, such as WiFi and sockets.
ujsonHandles encoding and decoding of data in JSON format.
ureProvides regular expressions in MicroPython.
ustructAllows efficient manipulation of binary data.
ubinasciiOffers functions for conversion between binary data and ASCII (Base64, hex, etc.).
randomGeneration of pseudo-random numbers.
mathMathematical functions like sine, cosine, square root, etc.
builtinsContains built-in Python 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 executing

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 we can download and use libraries developed by third parties in our projects.