CircuitPython Storage

You have been using that little USB drive to put code on, but maybe you've wondered "Hey can I write data from Python to the storage drive to act as a datalogger?" The answer is yes (as of CircuitPython 2.0.0)!

But it is a little bit tricky - you need to add some special code to boot.py not just main.py. That's because you have to set the filesystem to be read-only when you need to edit code to the disk from your computer, and set it to be write-able when you want the CircuitPython core to be able to write.

You can only have either your computer edit the CIRCUITPY drive files, or CircuitPython. You cannot have both write to the drive (Bad Things Will Happen so we do not allow you to do it!)

Here is your new boot.py:

import digitalio
import board
import storage

switch = digitalio.DigitalInOut(board.D0)
switch.direction = digitalio.Direction.INPUT
switch.pull = digitalio.Pull.UP

# If the D0 is connected to ground with a wire
# CircuitPython can write to the drive
storage.remount("/", switch.value)

And here is the main.py

import board
import digitalio
import microcontroller
import time

led = digitalio.DigitalInOut(board.D13)
led.switch_to_output()

try:
    with open("/temperature.txt", "a") as fp:
        while True:
            temp = microcontroller.cpu.temperature
            # do the C-to-F conversion here if you would like
            fp.write('{0:f}\n'.format(temp))
            fp.flush()
            led.value = not led.value
            time.sleep(1)
except OSError as e:
    delay = 0.5
    if e.args[0] == 28:
        delay = 0.25
    while True:
        led.value = not led.value
        time.sleep(delay)
boot.py only runs on first boot of the device, not if you re-start the REPL with ^D or if you save the file, so you must EJECT the USB drive, then physically press the reset button!

Eject & unplug the Trinket or Gemma once you have written these files. Then connect a wire from D0 to ground. This will enable the internal filesystem writing. Now power up the board again.

You will not be able to edit code on the CIRCUITPY drive anymore!

The red LED should blink once a second and you will see a new temperature.txt file.

This file gets updated once a second but you wont see data come in live. Instead, when you're ready to grab the data, remove the D0 wire and re-plug-in the Trinket/Gemma (or press the reset button). Now it will be possible for you to write to the filesystem from your computer again, but it will not be logging data.

We have a more detailed guide on this project available here https://learn.adafruit.com/cpu-temperature-logging-with-circuit-python

Last updated on 2017-12-01 at 04.59.09 PM Published on 2017-08-23 at 05.57.02 PM