Wednesday 19 September 2018

CircuitPython: writing to the file system.

Circuitpython has a very easy way of uploading code and data to the microcontroller, the microcontroller's storage appears as a USB storage device on the host's operating system. To move code and data to the microcontroller, you simply copy everything to the volume.

Unfortunately this does mean that, by default, Circuitpython cannot write data to its own storage (it is read only) and so it cannot write data that will visible to the host.

However it is possible to change that in the optional boot.py code file.

The boot.py file is only run on the first boot of the device (power up) and not when REPL is restarted or when you save a file. The microcontroller needs to be Ejected as a USB device and the reset button pressed.

Note: When you change it from read only, it is not possible to update the code on the microcontroller - including the boot.py.

The boot.py file needs to contain the following code:
import storage
storage.remount("/", False)

The first line imports the storage module, allowing access to OS functions.
The second line remounts the storage with readonly set to false.

The boot.py file can be "removed" via REPL (Read - Evaluate - Print - Loop). This is very like a command line interface combined with an (xPython) interpretor.

To access REPL on Mu:
Click on the Serial button on the ribbon. This will open a serial connection to the connected microcontroller.
Press CTRL-C (keyboard interrupt) to stop CircuitPython from continuing with whatever it is doing.
Press any key (as instructed).
Use the REPL.

To remove the boot.py, you need to rename the file via REPL:
import os
os.listdir("/")
os.rename("/boot.py", "/boot.bak")

The first line imports the storage module, allowing access to OS functions.
The second lists the contents of the root of the microcontoller's storage.
The third renames the boot.py file to boot.bak.

The microcontroller needs to be ejected (as a USB device) and the reset button pressed (physically unplugging it after ejecting it will also work).

References

https://codewith.mu/en/tutorials/1.0/repl
https://learn.adafruit.com/cpu-temperature-logging-with-circuit-python/writing-to-the-filesystem
https://circuitpython.readthedocs.io/en/2.x/shared-bindings/storage/__init__.html

MU Python, Micropython and CircuitPython editor

The Micro:bit can be programmed offline using the Mu editor. Until recently the editor available on the Raspbian repository has been an earlier version without support for the Radio module.

For a Raspberry Pi, Mu is now included in the Recommended Software option.

Instructions for installation are listed in the references.

References:

https://codewith.mu/
https://www.raspberrypi.org/blog/mu-python-ide/
https://projects.raspberrypi.org/en/projects/getting-started-with-mu