Files on a micro:bit?

Some ideas require that small amounts of data be saved for future use. It would be ideal if this was possible on the micro:bit. MicroPython provides the tools to allow this.

MicroPython is an implementation of Python 3 that has been developed to run on microcontrollers with a version developed for the micro:bit.

Tutorials and documentation for the micro:bit version can be found here.

The tutorials and documentation releveant to storage on the micro:bit can be found at 'storage' and in the API documentation at 'local persistent storage'.

Below is a quick demo which will create a file, insert a line, open the file for reading and then display the contents of the line from the file:

  • Start a new Python project at microbit.org
  • Clear all the default 'hello world' code
  • Enter the following code in its place:
from microbit import *  
import os

with open('hello.py', 'w') as newFile:  
    newFile.write("The file was created")

with open('hello.py') as file:  
    output=file.readline()

display.scroll(output)  
  • Download it to the micro:bit and watch the output.

When experimenting remember that re-flashing the device will destroy any previously stored data.

This is due to that any storage will be placed in the the micro:bit's flash memory and this is completely rewrote each time you flash your created code. However, one advantage of this type of memory is that anything stored will not be lost upon power removal.

Also as there is only around 30KB of storage any usage needs to be tightly controlled.