This tutorial shows how to dynamically load modules on a remote Micropython python device. When does this come in handy? Sometimes you want to use the LMS-ESP32 board for different projects. It can be cumbersome to reflash it every time. For this situation, we created the
UartRemote.add_module method. Issuing this command from your LEGO hub allows you to load scripts and libraries dynamically on the LMS-ESP32 board over a serial connection.
Two Micropython application modules on one LMS-ESP32 board
Suppose you have two applications programmed on the LMS-ESP32 board. For example, the first is driving an LED matrix. You put the code in
led.py, on the flash of the LMS-ESP32. The second application is a temperature sensor, with the code stored in
To control the led, you can use
ur.add_module('led') to load the
led module. Next, you can execute
ur.call('led','repr', 90). This command lights the LED at 90 degrees with the circular LED array.
If another program on the LEGO hub needs to read a temperature, it can also import its proper module. For this, you use the
ur.add_module('temperature') command. Next, you can execute
ur.call('read_temp') to read the temperature.
The tutorial uses two dummy classes to show how the
add_module feature works.
Video tutorial on remotely importing Micropython modules on the LMS-ESP32 board from the MINDSTORMS hub
Code used in this tutorial
You have to save three scripts (main.py, led.py, and test.py) to the local flash filesystem of the LMS-ESP32 to get this tutorial working. You can do that by loading the code in Thonny and saving the code using ‘Save as.’ Choose ‘MicroPyhton device’ when you do. After rebooting,
main.py executes, and the UartRemote
loop() is waiting for calls from the Lego hub.
Need more help with MicroPython modules, LEGO Hubs, and electronics?
This tutorial is part of a multi-part tutorial. First, we set up the hardware, then we explain communication; next, you’ll learn about controlling RGB LEDs and then about I2C joysticks. You can also load MicroPython modules dynamically with our library. And there are more libraries to come.
We’d love to see what you build, and maybe we can help you with some questions. Drop us a line on Facebook!