Skip to main content Link Menu Expand (external link) Document Search Copy Copied

MicroPython API


MicroPython lets you prototype and build your applications quickly without having to dive into any low level programming. With a few lines of Python, you can draw to the display, access the camera, and offload processing to the FPGA. Of course you get all the other benefits of Python too. Best of all, it’s completely wireless, and you can access the Python REPL fully over Bluetooth.

The MicroPython firmware for Monocle is a customized firmware which is largely based on the upstream MicroPython project. Thanks to the large MicroPython community, we’re always updating to new features as they come out on the upstream project.

A subset of the standard MicroPython libraries are currently supported, with more periodically being added. Additionally, some extra modules are included which let you easily interact with the Monocle hardware. Be sure to check out the MicroPython docs site, as well as the docs here to familiarize yourself with all the features.


Quick start

Check that you’re on the latest firmware.

Get started by trying out the Web Bluetooth REPL using Google Chrome on your PC, Mac, or Android, or use a Web Bluetooth compatible web browser on your iOS device such as Bluefy.

Accessing MicroPython on Monocle using the web REPL interface

Once you’re connected, try running this code:

import touch
import display

fn change_text():
    display.fill(0)
    display.text("touched!", 0, 0, 0xffffff)
    display.show()

touch.bind(touch.A, touch.TAP, change_text)

display.fill(0)
display.text("tap touch A", 0, 0, 0xffffff)
display.show

Mobile app

We’re gradually building our companion app along with some extra features to help you get the most out of Monocle. It’s also a great place to start if you’d like to make your own app, and the source code is freely available on our GitHub.

Apple App Store badge        Google Play Store badge


Library reference

MicroPython for Monocle is always being updated so be sure to check back frequently. The ❌ icon signifies a feature which is not implemented yet, but is planned.

  1. builtins
  2. device – Monocle specific
  3. display – Monocle specific
  4. camera – Monocle specific
  5. microphone – Monocle specific
  6. touch – Monocle specific
  7. led – Monocle specific
  8. fpga – Monocle specific
  9. storage - Monocle specific
  10. bluetooth - Monocle specific
  11. time – Monocle specific
  12. gc
  13. math
  14. micropython
  15. uasyncio
  16. ubinascii
  17. uerrno
  18. uio
  19. ujson
  20. urandom
  21. ure

builtins

The majority of built in functions are supported, along with some extended features below. Some less important features are not included to save on space for other things. If you feel we’ve missed something, create an issue on our GitHub, and we’ll try to add it.

MembersDescription
bytearray classByte arrays are supported.
dict classDictionaries are supported.
enumerate classEnumerate loops are supported.
float classFloating point numbers are supported.
max() functionThe max function is supported.
min() functionThe min function is supported.
reversed classReversing lists are supported.
set classSets are supported.
slice classSlices are supported.
str classUnicode and string handling is supported.

device – Monocle specific

The device class contains general information about the Monocle’s hardware and firmware.

MembersDescription
NAME constantConstant which holds 'monocle' as a string.
mac_address() functionReturns the 48-bit MAC address as a 17 character string in the format 'xx:xx:xx:xx:xx:xx', where each xx is a byte in lowercase hex format.
VERSION constantConstant containing the firmware version as a string. E.g. 'monocle-firmware-v22.342.1252'.
GIT_TAG constantConstant containing the build git tag as a 7 character string.
battery_level() functionReturns the battery level percentage as an integer.
reset() functionResets the device.
reset_cause() functionReturns the reason for the previous reset or startup state. These can be either:
- 'POWERED_ON' if the device was powered on normally
- 'SOFTWARE_RESET' if reset() or update() was used
- 'CRASHED' if the device had crashed.

display – Monocle specific

The display module allows for drawing to the micro OLED display. An image can be prepared using the functions below, and then show() can be used to print the image to the display.

MembersDescription
fill(color) functionFills the entire display with a color. color should be a 24-bit RGB value such as 0xAABBCC.
pixel(x, y, color) functionDraws a single pixel of color color at the position x, y.
hline(x,y,width,color) functionDraws a horizontal line from the position x, y, with a given width and color.
vline(x,y,height,color) functionDraws a vertical line from the position x, y, with a given height and color.
line(x1,y1,x2,y2,color) functionDraws a straight line from the position x1, y1, to the position x2, y2, with a given color.
text("string",x,y,color) function ❌Draws text at the position x, y, with a given color.
show() functionPrints the populated frame buffer to the display. After this call, another series of drawing functions may be called and show() can be used to print the next frame.
power(power_on) functionPowers up the display if True is given otherwise powers down with False. If no argument is given, the current powered state of the display is returned.
ON constantEqual to True. For use with display.power(). Used to turn the display on.
OFF constantEqual to False. For use with display.power(). Used to turn the display off.

camera – Monocle specific

The camera module allows for capturing images and transferring them to another device over Bluetooth.

MembersDescription
capture() functionCaptures an image and returns it to a device over Bluetooth. See downloading media to understand how media transfers are done.
power(power_on) function ❌Powers up the camera if True is given otherwise powers down with False. If no argument is given, the current powered state of the camera is returned.
ON constantEqual to True. For use with camera.power(). Used to turn the camera on.
OFF constantEqual to False. For use with camera.power(). Used to turn the camera off.

microphone – Monocle specific

The microphone module allows for capturing audio and streaming it to another device over Bluetooth.

MembersDescription
stream() function ❌Streams audio from the microphone to a device over Bluetooth. See downloading media to understand how media transfers are performed.

touch – Monocle specific

The touch module allows for reacting to touch events from the capacitive touch pads on Monocle.

MembersDescription
bind(pad,action,callback) function Attaches a touch action (either TAP, DOUBLE_TAP, LONG_PRESS or SLIDE) on a specific pad (A, or B) to a callback function. callback can be any python function or lambda function which will be triggered on the event.
state(pad) functionReturns the current touch state of the pad A or B. Returns either True if the pad is pressed, otherwise returns False.
A constantEnumeration which represents Pad A.
B constantEnumeration which represents Pad B.
TAP constantEnumeration which represents a single tap action.
DOUBLE_TAP constantEnumeration which represents a double tap action.
LONG_PRESS constantEnumeration which represents a long press or hold of 1 second.
SLIDE constantEnumeration which represents a slide action from A to B, or B to A. the pad argument in bind() is considered to be the starting pad.

led – Monocle specific

The LED module contains functions to control the red and green LED on the front of Monocle.

MembersDescription
on(color) functionIlluminates an led. color can be either led.RED or led.GREEN.
off(color) function Turns off an led. color can be either led.RED or led.GREEN.
RED constantEnumeration of the red led which can be passed to led.on() or led.off().
GREEN constantEnumeration of the green led which can be passed to led.on() or led.off().

fpga – Monocle specific

The FPGA module allows for direct control of the FPGA, as well as the ability to update the bitstream.

MembersDescription
read(addr, n) functionReads n number of bytes from the 16-bit address addr, and returns a bytes object.
write(addr,bytes[]) functionWrites all bytes from a given bytes object bytes[] to the 16-bit address addr.
power(on) functionPowers up the FPGA if True is given otherwise powers down with False. If no argument is given, the current power state of the FPGA is returned.
update(url) functionDownloads and reboots the FPGA with a bitstream provided from the url. Automatically wakes up the FPGA if it is shutdown. If the update is interrupted part way through, the FPGA will no longer be running a valid application, and must be updated again. See FPGA bitstream updates to understand how the update process is done.
status() functionReturns the current status of the FPGA:
- 'RUNNING' if the FPGA is running a valid bitstream.
- 'NOT_POWERED' if the FPGA is not powered
- 'BAD_BITSTREAM' if the FPGA cannot run the bitstream stored in memory. In this case, another update() must be performed.
ON constantEqual to True. For use with fpga.power(). Used to turn the FPGA on.
OFF constantEqual to False. For use with fpga.power(). Used to turn the FPGA off.

storage - Monocle specific

Storage can be used for reading or writing to files within the non-volatile storage. "file" can be any user defined string, however certain strings are reserved for special uses such as "fpga-bitstream" which is used to store the FPGA application.

MembersDescription
read("file",offset,length) function ❌Reads and returns a bytes object from a file within the non-volatile storage. offset is an optional position in bytes from the start of the file to read from. Optionally, passing length determines how many bytes to read out, otherwise the full file is returned.
create("file", bytes[]) functionCreates a new file with name "file" and populates it with data from a bytes object bytes[].
append("file", bytes[]) functionAppends data from a bytes object bytes[] to the end of an existing file.
delete("file") functionDeletes a file from the storage.
list() functionLists all files currently on the device.
FPGA_BITSTREAM constantA special filename which is used for storing the FPGA bitstream. This file can not be deleted, and must be populated for the FPGA to start up.

bluetooth - Monocle specific

The bluetooth module can be used to transfer byte data between Monocle and the host Bluetooth device. Bytes can contain any arbitrary data, and avoids having to pollute the REPL interface with printing data out as strings. The raw data service is used for all communications under the bluetooth module.

MembersDescription
send(bytes[]) function ❌Sends data from a bytes object bytes[] over Bluetooth using the raw data service. The length of the bytearray must be equal to or less than the MTU size - 3. This value may be obtained using the bluetooth.max_length() function.
receive() functionReceives data over the raw data service and returns a bytes object.
max_length() functionReturns the maximum negotiated payload size for Bluetooth transfers.
connected() functionReturns True if the raw data service is connected, otherwise returns False.

time – Monocle specific

The time module allows for getting/setting the time and date as well as adding delays into your programs.

MembersDescription
epoch(secs) functionSets or gets the current system time in seconds. If secs is not provided, the current time is returned, otherwise the time is set according to the value of secs. secs should be referenced from midnight on the 1st of January 1970.
zone(offset) functionSets or gets the time zone offset from GMT as a string. If offset is provided, the timezone is set to the new value. offset must be provided as a string, eg “8:00”, or “-06:30”.
time(epoch) functionReturns a dictionary containing a human readable date and time. If no argument is provided, the current system time is used. If epoch is provided, that value will be used to generate the dictionary. The epoch should be referenced from midnight on the 1st of January 1970.
mktime(dict) functionThe inverse of time(). Converts a dictionary provided into an epoch timestamp. The returned epoch value will be referenced from midnight on the 1st of January 1970.
sleep(secs) functionSleep for a given number of seconds.
sleep_ms(msecs) functionSleep for a given number of milliseconds.
ticks_ms() functionReturns a timestamp in milliseconds since power on.

gc

Standard MicroPython garbage collection is supported.

math

Standard MicroPython math functions are supported.

micropython

Standard MicroPython internals are supported.

uasyncio

Standard MicroPython asynchronous scheduling is supported.

ubinascii

Standard MicroPython binary/ASCII conversions are supported.

uerrno

Standard MicroPython system error codes are supported.

uio

Standard MicroPython IO streams except for FileIO are supported.

ujson

Standard MicroPython JSON handling is supported.

urandom

Standard MicroPython random number generation is supported.

ure

Standard MicroPython regular expressions are supported.


Under the hood

This section describes how data is transferred to and from Monocle over Bluetooth.

Communication

All MicroPython communication, i.e. the REPL interface, is accessed via a single Bluetooth Service containing two Characteristics.

  • Serial service UUID: 6e400001-b5a3-f393-e0a9-e50e24dcca9e
  • Serial RX characteristic UUID: 6e400002-b5a3-f393-e0a9-e50e24dcca9e
  • Serial TX characteristic UUID: 6e400003-b5a3-f393-e0a9-e50e24dcca9e

The RX characteristic is write only, and transports serial string data from the central BLE device to Monocle. The TX characteristic is notification only and delivers messages back from Monocle, to the central BLE device.

Each characteristic transports string data of any length up to the negotiated MTU size - 3 bytes. Longer strings must be chopped up and will be automatically rejoined on the receiving side by Monocle. Likewise if Monocle wishes to send longer responses than can fit into a single MTU payload, the data will arrive sequentially, and can be concatenated by the central Bluetooth app. The diagram below describes how communication operates between Monocle and a central device.

Sequence diagram of the Monocle serial data service

A secondary Bluetooth Service, again containing two Characteristics, is used to transport raw data such as image, audio and firmware update data. The mechanism for the raw data service is similar to the serial data service, aside from the fact that null or 0 characters may also be included within the payload.

  • Raw data service UUID: e5700001-7bac-429a-b4ce-57ff900f479d
  • Raw data RX Characteristic UUID: e5700002-7bac-429a-b4ce-57ff900f479d
  • Raw data TX Characteristic UUID: e5700003-7bac-429a-b4ce-57ff900f479d

Raw data transfer may often be bigger than a single MTU payload. Similarly to the serial data, it may need to be broken up into pieces. To help reconstruct the packets sent or received by Monocle, a flag is present at the start of each payload to determine if it’s either a starting payload, middle payload, end payload, or a small single buffer payload. The exact mechanisms for different types of data transfer are outlined below.

Downloading media

Media files such as audio and images may be downloaded from the Monocle using the raw data service mentioned in the Communication section. Files may also be sent asynchronously by Monocle when they are ready.

Due to the small payload size of Bluetooth packets, the file may be spit into many chunks and need to be recombined by the receiving central device. A flag at the start of each payload indicates if it is the START, MIDDLE or END of the file. A very small file may also be transferred using the SMALL flag.

The first payload includes metadata about the file such as the filename (with a relevant file extension) and the file size. The sequence diagram below describes how a file is broken into several parts and the data can be recombined to construct the full file:

Sequence diagram of the Monocle raw data service

Firmware updates

Updates of the MicroPython firmware are handled using Nordic’s over-the-air device firmware update process.

To perform an update:

  1. Check which version of the firmware you current have by entering import device; device.VERSION.

  2. Download the latest monocle-vXX.XXX.XXXX.zip package from our GitHub releases page.

  3. Issue an update command over MicroPython using import device; device.update(). Monocle will now reboot into DFU mode.

  4. Using the nRF Connect App, for desktop, Android, or iOS, you can reconnect to Monocle, select the downloaded .zip file, and update to the latest version.

FPGA bitstream updates

Details coming soon.