Importing MicroPython User Defined Modules

Contents

Introduction

Module refers to any MicroPython file saved with the .py extension. Modules contain code such as functions, classes and statements.

The term Library is used to refer to a collection of modules that are used repeatedly in various programs without the need of writing them from scratch. The components of libraries and modules can be imported and used within other programs, thus promoting the reuse of code.

Python comes installed with a standard library that simplifies common programming tasks. As MicroPython is a “slimmed down” Python specifically designed for the programming of microcontrollers it implements many parts of the Python standard library but omits components that are irrelevant to this purpose.

Import Statement

The import statement is the easiest way to expose another module or library to a MicroPython program. It works similarly to the #include in C/C++.

The syntax is simple:


Basic Syntax:
import module-name

Alternative Syntax:
import module-name as name

Where:
  name is a synonym for the module name.

Examples:
import math
print(math.sqrt(5))  ⇒ 2.236068 

import math as m
print(m.log(5))  ⇒ 1.609438
          

The imported module must be a file with an extension of .py and containing only code that can be interpreted by the MicroPython interpreter. A word processing application such as Microsoft Word which inserts formatting symbols amidst the text is not a suitable editor to create such a file.

This series is all about running MicroPython programs on a microcontroller; specifically a BBC micro:bit. The Mu Editor is highly recommended for those fairly new to this microcontroller platform. It provides an easy to use code editor to create the program and then flash it to the microcontroller.

Flashing causes the MicroPython program to be copied to the micro:bit where it is automatically renamed to main.py. At this point the MicroPython interpreter is invoked and main.py is executed.

It is important to realise that when the MicroPython program is executed, the actual code file is now located in the flash memory of the microcontroller. The micro:bit cannot execute a program located in the file system of the computer used to perform the program flash.

This means, to use an imported module, that module's file must physically exist on the microcontroller. Using the Mu editor this is an easy task. The process is best explained with a simple example.

From Mu Editor, open a new file by clicking the New button then copy the Example 1A code to the editor. Click the Save button and save the file with the name World.py.

Example 1A

# World.py
#
# MicroPython module with two simple functions
# Useful for testing the 'import' statement

def Hello():
    print('Hello World!')
    
def Earth():
    print('This world is called Earth!')
          

This World.py file needs to be copied to the micro:bit's flash memory. Ensure that the REPL window in Mu is not open. If it is then the Flash and File buttons will be greyed out.

Click the File button. The bottom section of the Mu Editor will now show a split panel with two panes, very similar to most FTP programs. The left side pane shows the files on the micro:bit and the right side pane shows the files on the computer.

Locate the file World.py in the right side pane and drag it to the left side pane. The file will now be copied to the microcontroller's non-volatile memory.

Start a new program in the Mu editor and copy the Example 1B code. Save and flash it to the micro:bit.

Example 1B

# A program to test 'import' on a micro:bit

import World

World.Hello()
World.Earth()

          
Output:

Hello World!
This world is called Earth!
          

Note that the module name in the import statement is not suffixed with the file type (py). Also when the functions in the imported module are called they must be qualified with the module name; in this case World.Hello() and World.Earth()

Extended Import Statement

The import statement also has an extended version with the following syntax:

Syntax:
from module-name import obj_1
          [, obj_2, ..., obj_n]

Where:
  obj_1, obj_2, obj_n : are the names of
  one or more functions that are found
  in the module.

Example:
from math import sqrt
print(sqrt(5))  ⇒ 2.236068
          

Example 1B could be slightly rearranged using this form of the import statement.


# A program to test 'import' on a micro:bit

from World import Hello, Earth

Hello()
Earth()

          

To complete this discussion here is a 'real-life' example. The standard math library has an excellent selection of trigonometry functions. These functions expect arguments in units of radians, where in many cases, degrees of angle, would be more useful.

The next example creates the module trig that accepts arguments in degrees for the standard trigonometric functions.

Copy the code of Example 2A into a new file on the Mu editor and save it using trig.py as the name. Copy this file to the micro:bit.

Example 2A

# This file contains alternative
# trigonometric functions to those
# provided in the Python standard
# library 'math'.

# Engineers in the field often prefer
# to use trigonometric functions that
# use degrees instead of radians as
# required by the 'math' library.

# The functions in this file all accept
# or return degrees, eg:
# trig.sin(60) = 0.8660254 and
# trig.asin(0.8660254) = 60

import math

def d_to_r(degrees):
    # Accepts an arguement in degrees and
    # returns equivalent radians.
    return degrees / 180 * math.pi

def r_to_d(radians):
    # Accepts an arguement in radians and
    # returns equivalent degrees.
    return 180 / math.pi *radians
    
def sin(degrees):
    return math.sin(d_to_r(degrees))

def asin(value):
    return r_to_d(math.asin(value))

def cos(degrees):
    return math.cos(d_to_r(degrees))

def acos(value):
    return r_to_d(math.acos(value))
    
def tan(degrees):
    return math.tan(d_to_r(degrees))
    
def atan(value):
    return r_to_d(math.atan(value))

          

Copy Example 2B to a new file in the Mu editor, save and flash to the micro:bit.

Example 2B

import trig

# The imported 'trig' module supports the
# standard trigonometry functions using
# degrees instead of radians as required
# in the standard Python 'math' library.

print('Sin(60) =', trig.sin(60))
print('Cos(60) =', trig.cos(60))
print('Tan(60) = ', trig.tan(60))

print()

print('Testing Arcsin:',
       trig.asin(trig.sin(60)))
print('Testing Arccos:',
       trig.acos(trig.cos(60)))
print('Testing Arctan:',
       trig.atan(trig.tan(60)))

          
Output:

Sin(60) = 0.8660254
Cos(60) = 0.5
Tan(60) =  1.732051

Testing Arcsin: 60.0
Testing Arccos: 60.0
Testing Arctan: 60.0

          

This example demonstrates good programming practice. The standard trigonometry functions in math have been well tested and are extensively used by many programmers.

It doesn't make sense to completely rewrite these functions i.e “re-invent the wheel”.

So the module trig uses these functions as its foundation and simply extends them with functions that perform radian to  (and vice versa) angle conversions.