Modules and libraries in MicroPython allow you to extend the functionality of your program by importing additional code, enabling you to interact with hardware, handle time-based functions, perform mathematical operations, and much more. In this guide, we’ll explore how to use modules like machine for hardware control, time for time-based functions, os for file system operations, and more, to create efficient and powerful programs on ESP32 and ESP8266.
What are Modules and Libraries in MicroPython for ESP32 and ESP8266?
Modules in MicroPython are collections of functions and variables bundled together. Libraries are external code that can be imported to extend the capabilities of your program. By using modules, you avoid rewriting code for common tasks and can easily interact with hardware, perform computations, or manage files. MicroPython offers a wide range of built-in modules, and you can also install third-party libraries to add extra functionality.
Syntax Table for Modules and Libraries in MicroPython
Concept | Syntax | Simple Example |
import | import module_name | import machine |
from … import | from module import name | from math import sqrt |
as (aliasing) | import module as alias | import random as rnd |
machine | import machine | machine.Pin(5, machine.Pin.OUT) |
time | import time | time.sleep(1) |
os | import os | os.listdir() |
math | import math | math.sqrt(16) |
random | import random | random.randint(1, 10) |
urequests | import urequests | urequests.get(‘http://example.com’) |
ujson | import ujson | ujson.dumps({“key”: “value”}) |
import in MicroPython for ESP32 and ESP8266
What is import in MicroPython?
The import statement allows you to bring in a module into your program so you can access its functions and variables. This is essential when using external libraries or built-in modules like machine or time.
Use purpose:
import enables you to add functionality to your program without rewriting code for common tasks like interacting with hardware or performing mathematical calculations.
Micropython Syntax use:
import module_name
Micropython Syntax Explanation:
This syntax imports the entire module, making all its functions and variables available in your program.
Micropython Code Example:
import machine
pin = machine.Pin(2, machine.Pin.OUT)
pin.value(1)
Notes:
- After importing a module, you need to use the module name when calling its functions or variables (e.g., machine.Pin).
Warnings:
- Importing large modules can consume memory, so be mindful of memory usage on ESP32 and ESP8266.
from … import in MicroPython for ESP32 and ESP8266
What is from … import in MicroPython?
The from … import statement allows you to import specific functions or variables from a module, rather than the entire module. This reduces memory usage and makes your code more efficient.
Use purpose:
Use from … import when you only need a few functions or variables from a module, minimizing the memory footprint of your program.
Micropython Syntax use:
from module import name
Micropython Syntax Explanation:
This syntax imports only the specified function or variable, making it available directly without the need to prefix it with the module name.
Micropython Code Example:
from math import sqrt
result = sqrt(16) # Output: 4.0
Notes:
- This method is memory-efficient, especially for large modules where you don’t need all the functionality.
Warnings:
- If you import multiple functions with the same name from different modules, it can lead to conflicts.
as (Aliasing) in MicroPython for ESP32 and ESP8266
What is as in MicroPython?
The as keyword allows you to assign an alias to a module. This is useful for shortening long module names or avoiding name conflicts.
Use purpose:
Aliasing makes your code more readable, especially if you’re importing modules with long names or using multiple libraries with similar names.
Micropython Syntax use:
import module as alias
Micropython Syntax Explanation:
This syntax imports a module and assigns it an alias. You can then use the alias to call functions from the module.
Micropython Code Example:
import random as rnd
print(rnd.randint(1, 10)) # Output: A random number between 1 and 10
Notes:
- Aliasing is commonly used to make code more concise.
Warnings:
- Be careful not to use an alias that conflicts with variable names in your program.
machine Module in MicroPython for ESP32 and ESP8266
What is the machine module?
The machine module is a hardware-specific library that allows you to interact with the GPIO pins, I2C, SPI, ADC, and other hardware features of the ESP32 and ESP8266.
Use purpose:
The machine module is essential for controlling hardware components like LEDs, sensors, and motors connected to the ESP32 and ESP8266.
Micropython Syntax use:
import machine
Micropython Code Example:
import machine
pin = machine.Pin(2, machine.Pin.OUT)
pin.value(1) # Turns on the GPIO pin
Notes:
- The machine module is platform-specific and provides low-level access to the microcontroller’s peripherals.
Warnings:
- Incorrect usage of the machine module can damage your hardware, so ensure you understand the wiring and functionality before using it.
time Module in MicroPython for ESP32 and ESP8266
What is the time module?
The time module provides functions related to time, such as delays, timing events, and measuring elapsed time.
Use purpose:
Use the time module to introduce delays, control timing, or measure how long a process takes to execute.
Micropython Syntax use:
import time
Micropython Code Example:
import time
time.sleep(1) # Pauses the program for 1 second
Notes:
- The time.sleep() function is commonly used to create delays in hardware control.
Warnings:
- Be careful with long sleep() times, as they block the execution of your program during the delay.
os Module in MicroPython for ESP32 and ESP8266
What is the os module?
The os module provides functions to interact with the file system, allowing you to read from and write to files stored in the flash memory of ESP32 and ESP8266.
Use purpose:
Use the os module for file system operations like listing files, reading from files, and writing data to files.
Micropython Syntax use:
import os
Micropython Code Example:
import os
print(os.listdir()) # Lists all files in the root directory
Notes:
- The os module is useful for saving data to the file system or retrieving configuration files.
Warnings:
- Ensure that your file system has enough space and that the proper permissions are set when reading or writing files.
math Module in MicroPython for ESP32 and ESP8266
What is the math module?
The math module provides mathematical functions, including trigonometric, logarithmic, and power functions.
Use purpose:
Use the math module for advanced mathematical operations, such as calculating square roots, powers, or trigonometric values.
Micropython Syntax use:
import math
Micropython Code Example:
import math
result = math.sqrt(25)
print(result) # Output: 5.0
Notes:
- The math module is useful for sensor data processing, where you need to perform calculations on raw values.
Warnings:
- The math module is optimized for performance, but large calculations may still consume significant resources on microcontrollers.
random Module in MicroPython for ESP32 and ESP8266
What is the random module?
The random module is used to generate random numbers, which are useful for creating random delays, simulations, or generating random data in your MicroPython programs.
Use purpose:
The random module is commonly used for tasks like generating random delays, selecting random items from a list, or creating random values for simulations.
Micropython Syntax use:
import random
Micropython Code Example:
import random
value = random.randint(1, 10)
print(value) # Output: A random integer between 1 and 10
Notes:
- The random.randint() function is often used to generate random integers within a specified range.
Warnings:
- Random number generation in MicroPython is pseudo-random, meaning the sequence of numbers may not be truly random, but rather determined by an initial seed value.
urequests Module in MicroPython for ESP32 and ESP8266
What is the urequests module?
The urequests module is a lightweight HTTP client for making requests to web servers. It supports basic HTTP methods like GET, POST, PUT, and DELETE, enabling your ESP32 or ESP8266 to interact with web services.
Use purpose:
The urequests module is used to fetch data from or send data to web servers, making it ideal for IoT applications, such as fetching sensor data from a remote server or uploading data to cloud services.
Micropython Syntax use:
import urequests
Micropython Code Example:
import urequests
response = urequests.get("http://example.com")
print(response.text)
response.close()
Notes:
- Always remember to close the response object after the request is complete to free up resources.
Warnings:
- Be mindful of memory usage when making requests, as large responses can quickly consume the available RAM on ESP32 or ESP8266 devices.
ujson Module in MicroPython for ESP32 and ESP8266
What is the ujson module?
The ujson module provides functions for parsing and generating JSON (JavaScript Object Notation) data. JSON is commonly used for exchanging data between a server and a web client or between IoT devices.
Use purpose:
The ujson module is essential for serializing Python objects to JSON format and deserializing JSON data back into Python objects, which is crucial for APIs, IoT communications, and data logging.
Micropython Syntax use:
import ujson
Micropython Code Example:
import ujson
data = {"temperature": 22.5, "humidity": 60}
json_data = ujson.dumps(data)
print(json_data) # Output: {"temperature": 22.5, "humidity": 60}
Notes:
- ujson.dumps() converts a Python dictionary into a JSON string, while ujson.loads() parses a JSON string back into a Python object.
Warnings:
- Ensure the data being serialized is JSON-compatible (e.g., lists, dictionaries, strings, numbers).
Common Problems and Solutions
- Memory Issues with Large Modules
- Problem: Importing large modules can cause memory issues on devices with limited RAM like the ESP32 or ESP8266.
- Solution: Use selective imports (e.g., from module import function) to only load the functions you need, or use memory-efficient modules.
- Import Errors
- Problem: Module not found error when trying to import a module that isn’t available in MicroPython.
- Solution: Verify that the module is supported in MicroPython, and check whether it needs to be installed manually or replaced with an alternative MicroPython-compatible module.
- Unexpected Behavior in urequests
- Problem: The program hangs or crashes when making HTTP requests due to resource constraints.
- Solution: Always close the response object after making requests to free up memory and avoid using large payloads.
- Incorrect JSON Parsing
- Problem: Trying to parse non-JSON data using ujson results in errors.
- Solution: Ensure the data being passed into ujson.loads() is a valid JSON string before parsing.
FAQ
Q: Can I create my own modules in MicroPython?
A: Yes, you can create custom modules by writing Python scripts and importing them using the import statement. Make sure the module is saved in the same directory as your main script or in a directory included in the search path.
Q: How do I free up memory after importing a large module?
A: You can use the gc.collect() function from the gc module to manually trigger garbage collection and free up unused memory after importing or using large modules.
Q: Can I use modules like urllib or requests from standard Python?
A: No, standard Python modules like urllib or requests are not available in MicroPython. Instead, you should use MicroPython-specific modules like urequests for HTTP requests.
Q: What’s the difference between json and ujson?
A: ujson is a lightweight version of Python’s standard json library, optimized for MicroPython. It has a smaller memory footprint but offers similar functionality for serializing and deserializing JSON data.
Q: How do I check which modules are available in MicroPython?
A: You can check the official MicroPython documentation or use the help(‘modules’) command in the MicroPython REPL to list all available modules.
Summary
Modules and Libraries in MicroPython for ESP32 and ESP8266 provide a wide range of functionalities, from hardware control with the machine module to handling HTTP requests with urequests and working with JSON data using ujson. By using the import, from … import, and as statements, you can bring in only the code you need, optimizing both memory and performance.
- import brings in an entire module, while from … import allows you to import specific functions or classes.
- machine enables hardware control, time handles delays and timing, and os interacts with the file system.
- math and random provide mathematical functions and random number generation, essential for many applications.
- urequests and ujson handle HTTP requests and JSON data, essential for IoT applications.
By mastering these modules and libraries, you can extend the functionality of your ESP32 and ESP8266 projects, making them more powerful and efficient.