Data Logging

../_images/python-logging3.png

Note

This feature is for micro:bit V2 boards only

The micro:bit V2 can log sensor data to a file on the micro:bit. After logging your data, plug the micro:bit into a computer and open MY_DATA.HTM on the MICROBIT drive to view your data in a web browser, or download it as a CSV file for use in a spreadsheet.

Set column labels

To set up data logging, you need to provide descriptions for your data. These will appear as the column headings:

import log

log.set_labels('temperature', 'sound', 'light')

This example will create three column headings titled temperature, sound and light.

The first column in your log holds the timestamp and will be added to every row of data. You can set the format of the timestamp when you set your column labels to MILLISECONDS, SECONDS, MINUTES, HOURS, DAYS or NONE if you want to disable the timestamp.

This example sets the format to record the time in ‘hours’:

import log

log.set_labels('temperature', 'sound', 'light', timestamp=log.HOURS)

Log rows of data

You can log data from any of the built-in sensors on your micro:bit:

import log

log.add({
  'temperature': temperature(),
  'sound': microphone.sound_level(),
  'light': display.read_light_level()
})

The example above adds an entry to the temperature, sound and light columns using values from the temperature sensor, the microphone and the light level sensor.

The headings and values are passed to log.add() using a dictionary.

A dictionary is a data structure that consists of key:value pairs inside curly brackets {}. Each entry contains the label and the value associated with it.

Instead of using dictionary values, you can alternatively use keyword arguments with log.add(). This example logs the same data:

import log

log.add(
        temperature=temperature(),
        sound=microphone.sound_level(),
        light=display.read_light_level()
)

Schedule log entries

You can use a scheduler to log data automatically at regular intervals:

import log

@run_every(s=30)
def log_data():
        log.add({
          'temperature': temperature(),
          'sound': microphone.sound_level(),
          'light': display.read_light_level()
        })

This example logs data every 30 seconds.

You can use multiple time unit parameters, so for example you could use @run_every(h=1, min=20, s=30, ms=50) to log data every 1 hour 20 minutes 30 seconds and 50 ms.

Exercises

  1. Try to make an seismometer to record the movement caused by earthquake by using the micro:bit and log these movements. Log it every 100 ms.
  2. Try to create a device that logs the compass heading every 5 seconds.