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 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
Copied!

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
Copied!

We can also import specific functions from a module:

from mathematics import add

result = add(7, 3)
print(result)  # Output: 10
Copied!

Standard MicroPython Modules

MicroPython includes a series of built-in modules specifically designed for working 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 execution delays.
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 and ASCII data (Base64, hex, etc.).
randomPseudo-random number generation.
mathMathematical functions like sines, cosines, square root, etc.
builtinsContains 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
Copied!

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.