The SAMD21 MicroPython port supports two ways of freezing modules to reduce their memory usage.

Internal Frozen Modules

The first way is by building a custom SAMD21 MicroPython firmware build which packs in .py files as frozen modules.  The modules folder inside the atmel-samd folder of the source code is where you should place modules that will be frozen into the firmware.  This process is just like freezing modules on the ESP8266 port (however note there is no scripts folder for 'less frozen' modules, only the modules folder).

External Frozen Modules

The second way to use frozen modules is by converting a Python source file into a .mpy frozen module file.  You can copy .mpy files onto the board's file system and import them just like importing Python source files and modules.  However .mpy files will consume less RAM compared to raw Python .py source files.

To generate a .mpy file it's easiest to use the Vagrant build VM described earlier in this guide.  Start the VM and enter its SSH terminal.  Then run the following command to change to the .mpy compiler directory:

cd ~/source/circuitpython/mpy-cross

Make sure you've built the mpy-cross tool already as the previous build firmware instructions mentioned.  If you skipped that step then first run the make command in the directory to build the tool.

Once the tool is built converting a .py file to a .mpy file is as easy as running it with the tool.  First copy your Python source .py file into the VM (remember any file in the vagrant subdirectory on the host machine will be copied into the /vagrant folder inside the VM).  

For example if you have test.py file with a few functions:

def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

Copy it into the vagrant folder on the host PC, then in the mpy-cross directory in the VM run the following command to covert test.py into test.mpy:

./mpy-cross /vagrant/test.py

After the tool runs you should see a test.mpy file in the vagrant folder on the host PC, right next to the test.py file.

Now copy test.mpy onto the SAMD21 MicroPython board's filesystem.  Remember you can just drag and drop with USB mass storage!

Note: To be sure the file is accessible to the MicroPython board, after copying it over unmount the USB drive and reset the board by pressing the reset button.

Open a serial REPL on the board and run the following code to confirm you can import the test.mpy file and call its functions:

import test
test.add(1, 1)
test.subtract(1, 1)

That's all there is to using .mpy files as external frozen modules!

This guide was first published on Oct 17, 2016. It was last updated on Mar 08, 2024.

This page (Frozen Modules) was last updated on Oct 15, 2016.

Text editor powered by tinymce.