Sometimes we want to hide the source code to the user visibility.
In C this is easy because C source code and C executable are separate files, but in python you only have source files that are compiled in runtime.
Micropython uses a tool named mpy-cross to build some components in the host machine and add them to the micropython compiled firmware. This tool can be also used to distribute precompiled python files, known as .mpy files, that only contains python bytecode, not python source code, and can be loaded in runtime by the micropython virtual machine.
- mpy files has two main advantadges
- Removes source code and offers bytecode compiled firmware distribution.
- Avoids compilation stage on the SBC, reducing RAM usage
- To build the .mpy file, you need an mpy-cross tool, this tool is created by micropython and sources can be download and build from Github.
Here you have the compiled windows version. - Note that SBC runs with micropython 1.13, so mpy-cross tool must be built from this version too.
Procedure
The steps are simple:
1 Create a python file with your source code. In our case:
#welcome.py print( "hello world" )
2 Unzip the compiled windows version and place in the same folder:
– Your micropython source file
– mpy-cross.exe
– cygwin1.dll
3 Compile the file with mpy-cross tool. This should generate welcome.mpy file.
4 Copy the .mpy file to the SBC memory
5 To run the .mpy file, import your mpy file as a normal module: