Add Python Modules to the microbit

howto

Introduction to Modules

Modules are a handy way of moving objects, such as functions and classes, out of your main script.

Each Python script on the microbit begins with the line:

from microbit import *

This imports everything (*) in the microbit module into the program.

We could only import certain objects from the microbit module:

from microbit import display

Importing the display module reveals the display functions. display.scroll("hello") would work but not sleep(20) because the sleep function was not imported.

Sometimes, when memory becomes tight, it is necessary to import only what your program needs.

Adding 3rd Party Modules

To control a servo we need to import a module to tell the microbit how to use it.

In this example, we’ll use this servo class on github.

Download the file but we cannot just copy the file to the microbit; it must be added to the Python filesystem within mu.

Upload the Module

To add a servo.py file click ‘files’ within mu. It lists the files on your computer and the files on the microbit.

Copy the servo.py file from your computer to the microbit by double-clicking it.

The servo.py file should be in the mu directory on your computer. On windows this is c:\users\username\mu_code.

Import the Module in your Script

In your python script you can import the Servo class from the servo.py file:

from microbit import *

from servo import Servo
# from servo.py import Servo class

Use the Module

Servo(pin0).write_angle(90)

Here the Servo class is called with the pin0 argument. It tells an instance of the class that the servo’s SIGNAL pin is connected to pin0.

It then calls the .write_angle function with the argument 90 to move the servo 90 degrees.

Where does mu Download Files?

Add Modules to the Microbit

Clicking the ‘files’ button in mu will list the files on the microbit and on your computer.

The files on your computer can be found:

Windows: c:\users\username\mu_code

To add files to mu they must be copied to this directory first. Files downloaded from the microbit will also be in this directory.

Notes

Share On
Facebook Twitter Google Plus

Published: December 23, 2016 Updated: December 23, 2016

Add Python Modules to the microbit

Add Python modules to the the microbit with mu editor.

Jez Dean
Teacher