Micro:bit— capturing temp and light and saving to PC using Python

David Watts
3 min readNov 2, 2020

--

I was having a tinker with the Micro:bit and wanted to share the process for setting up a basic application, taking some sensory inputs and capturing them to your computer over USB.

Setup

The easiest way I found was using Mu for writing the code for the Micro:bit device, and Thonny for writing the python code for the computer.

The only other setup is to go to Tools → Manage in Thonny and download the pySerial package.

Code

The Micro:bit program, copy and save to Mu (Micro:bit environment),

from microbit import *
display.show(Image.HAPPY)
sleep(2000)
for i in range(20):
sleep(1000)
time = running_time()
temp = temperature()
lightlevel = display.read_light_level()
display.scroll(i+1)
display.show(Image.SQUARE)
print(str(time) + "," + str(temp) + "," + str(lightlevel))
sleep(500)
display.show(Image.YES)
display.clear()

The PC program on my laptop to receive the files, copy to Thonny and save as .py.

import serial
import time
from datetime import datetime
ser = serial.Serial()
ser.baudrate = 115200
ser.port = "COM3" ##you will need to update this based on the serial port, you can use Mu for this
ser.open()
while True:
## add the time
data1 = str(ser.readline())
data1 = data1.replace("b","")
data1 = data1.replace("'","")
data1 = data1.replace("\\r\\n","")
if data1 is not None:
with open("datadump.txt", "a") as myfile:
myfile.write(str(datetime.now()) + "," + data1 + "\n")
print(data1)
ser.close()

Open notepad and save this file as datadump.txt, this is the headers for the CSV

pcdatetime,microbitruntime,temp,light

Steps

  1. Copy “microbitprogram.py” to the microbit, in my case using Mu. The smiling face tells you it’s running and to start the PC program.
  2. Run “PCprogram.py” on the PC.
  3. The Microbit will then:
  • Take a finite number of samples of temperature and light
  • Send each sample to the PC program by printing a formatted comma separated string
  1. The PC program will
  • Take the the formatted string from the microbit with running time, temperature and light reading
  • Append the datetime from the PC
  • Append to an existing txt file (headers already loaded) with a new line, following CSV convention

Example output

Output graphed (note, I put my hand over the device halfway through the sampling to demonstrate the light).

--

--