Skip to main content

60 minute activity: Detecting and Logging Magnetism with a micro:bit (Python)

Activity Sheet: Detecting and Logging Magnetism with a micro:bit (Python)

image of traces from physical activities


Overview

In this activity, you turn a BBC micro:bit into a magnetism data logger using Python. The micro:bit's built-in compass sensor measures magnetic force; your program sends the readings down the USB cable so the computer can draw live graphs of them.

Based on the blog post Detecting and Logging Magnetism with a micro:bit.

Time: about 45–60 minutes

Learning objectives

By the end of this activity, you will be able to:

•       Explain that the micro:bit's compass is a sensor that measures magnetic fields.

•       Write a Python loop that reads a sensor over and over.

•       Send labelled data from the micro:bit to a computer using serial.

•       Read a live graph and describe how a moving magnet changes the readings.

What you need

Item

Notes

BBC micro:bit

Any version; the compass is built in

USB cable

Must stay plugged in while you collect data

Computer with a web browser

Chrome or Edge works best for the MakeCode data viewer

MakeCode editor

makecode.microbit.org

Small magnets

Circular (disc or ring) magnets that can roll work best

Safety: keep magnets away from bank cards, phones and the computer itself. Small magnets are a choking hazard.

Part 1: Write the Python program

You will write a four-line program that reads the magnetic force on two axes, X and Y, and sends both values to the computer forever.

1.      Go to makecode.microbit.org and click New Project. Call it magnet-logger.

2.      At the top of the editor, switch from Blocks to Python.

3.      Delete any code already there and type in the program below. Indentation (the spaces at the start of a line) matters in Python.

def on_forever():
    serial.write_value("x", input.magnetic_force(Dimension.X))
    serial.write_value("y", input.magnetic_force(Dimension.Y))

basic.forever(on_forever)

4.      Click the Blocks tab to check: you should see a forever block holding two serial write value blocks. Switch back to Python.

How the code works

Line

What it does

def on_forever():

Defines a function called on_forever. The indented lines under it are its body.

input.magnetic_force(Dimension.X)

Reads the magnetic force along the micro:bit's X axis (left to right across the board).

serial.write_value("x", …)

Sends that reading to the computer over USB, with the label x.

Third line

Does the same for the Y axis (top to bottom), labelled y.

basic.forever(on_forever)

Tells the micro:bit to run on_forever again and again, so new readings keep arriving.

The labels "x" and "y" matter: the data viewer uses them to draw a separate graph for each axis.

Check your understanding

1.      Why do we send the readings to the computer instead of showing them on the LEDs?

2.      What would happen if you removed the line basic.forever(on_forever)?

3.      Which part of the code would you change to label the first value side instead of x?

Part 2: Log the data and run the experiment

With the program running and the USB cable plugged in, the MakeCode data viewer draws live X and Y graphs as you move magnets near the micro:bit.

Download and open the data viewer

1.      Plug the micro:bit into the computer with the USB cable.

2.      Click Download (pair the micro:bit if MakeCode asks). Keep the cable connected afterwards: the data travels along it.

3.      Under the simulator, click Show data Device. A viewer opens with two traces, one for x and one for y.

4.      If the micro:bit asks you to calibrate the compass ("TILT TO FILL SCREEN"), tilt it until every LED is lit.

The experiment

1.      Lay the micro:bit flat on the table and leave it still for 10 seconds. Note what the graphs look like with no magnet nearby.

2.      Roll a circular magnet slowly alongside  the micro:bit, then  rock back and forth near the board.

3.      Watch both graphs. In the original demonstration, both traces showed a clear wave-like pattern as the magnet rocked.

4.      Repeat with the magnet approaching from a different side.

Record your results

Test

What the X graph did

What the Y graph did

No magnet (baseline)

 

 

Magnet rolled towards the board

 

 

Magnet rocking back and forth

 

 

Magnet from a different side

 

 

 

 

Part 3: Think about it

1.      Why did the graphs make a wave shape when the magnet rocked back and forth?

2.      Why might the X and Y graphs look different from each other?

3.      The readings were not zero with no magnet nearby. What magnetic field was the micro:bit detecting?

4.      How could this logger be useful in a real-world job?

Extension challenges

Challenge 1: Add the third axis. Add a line that sends the Z axis (through the board) with the label z. Where does the magnet need to be to change Z the most?

Challenge 2: Total strength. Dimension.STRENGTH gives the overall strength of the field. Send it with the label strength and compare it with the X and Y graphs.

Challenge 3: Magnet alarm. Make the micro:bit show a tick when a magnet is close. First check your baseline reading, then pick a threshold well above it.

def on_forever():
    strength = input.magnetic_force(Dimension.STRENGTH)
    serial.write_value("strength", strength)
    if strength > 200:
        basic.show_icon(IconNames.YES)
    else:
        basic.clear_screen()

basic.forever(on_forever)

Challenge 4: Save your data. Use the download button in the data viewer to save your readings as a CSV file, then open it in a spreadsheet and make a chart.

Troubleshooting

Problem

Try this

No Show data Device button

Check the USB cable is connected and the program has downloaded. Use Chrome or Edge.

Graphs are flat

Bring the magnet closer; check you typed magnetic_force, not compass_heading.

Error in the Python code

Check the indentation, the colon after def on_forever(), and capital letters in Dimension.X.

"TILT TO FILL SCREEN" appears

Tilt the micro:bit until every LED is lit to calibrate the compass.

Further reading

•       Original post: Detecting and Logging Magnetism with a micro:bit

•       Introductory video by Mr Morrison on the micro:bit detecting magnetic fields: YouTube

All opinions in this blog are the Author's and should not in any way be seen as reflecting the views of any organisation the Author has any association with. Twitter @scottturneruon

Comments

Popular posts from this blog

Programming Anki's Vector robot

With the sad news that Anki is shutting down ( https://www.vox.com/2019/4/29/18522966/anki-robot-cozmo-staff-layoffs-robotics-toys-boris-sofman ) I thought it was time I start playing with the SDK for the Vector robot. In this short post, I providing a quick overview of getting going with this with a simple program based on the tutorials Anki provide. Installation I am using a Mac (more details are available here  https://developer.anki.com/vector/docs/install-macos.html ) but there are instructions for Windows and Linux. - You need the Vector to have been set-up previous on a tablet, and an account set-up on the Anki Cloud. - Install Homebrew - available here  https://brew.sh/ - Using Homebrew to install Python3  brew install python3 -Now install the SDK  python3 - m pip install -- user anki_vector - Lst but not least configure the set-up  python3 - m anki_vector . configure - that is it. The configuration tool tells you where the serial...

Speech Recognition in Scratch 3 - turning Hello into Bonjour!

The Raspberry Pi Foundation recently released a programming activity Alien Language , with support Dale from Machine Learning for Kids , that is a brilliant use of Scratch 3 - Speech Recognition to control a sprite in an alien language. Do the activity, and it is very much worth doing, and it will make sense! I  would also recommend going to the  machinelearningforkids.co.uk   site anyway it is full of exciting things to do (for example loads of activities  https://machinelearningforkids.co.uk/#!/worksheets  ) . Scratch 3 has lots of extensions that are accessible through the Extension button in the Scratch 3 editor (see below) which add new fun new blocks to play with. The critical thing for this post is  Machine Learning for Kids  have created a Scratch 3 template with their own extensions for Scratch 3 within it  https://machinelearningforkids.co.uk/scratch3/ . One of which is a Speech to Text extension (see below). You must use this one ...

Scratch and web-cams in Scratch 3

Scratch 3 was launched on 2nd January 2019, so I wanted to know would Webcams still work with Scratch 3 as it did with Scratch 2. For example, in a previous post  Scratch, webcams, cats and explosions  the cat (Scratch) moved across the screen and a button burst when the object moved in the camera onto it.  Can the same thing be done in Scratch 3? The short answer is yes, but it is done slightly differently. The first change the video capture is not there in the blocks automatically; but is an extension that needs to be added. First, you need to add the extension blocks for video sensing. Go to the little icon at the bottom left of the screen (as shown below) this takes you to the extensions menu. Next, find the Video Sensing option and selected. The webcam, if enabled, with start automatically. A video sensing set of blocks is now in the list of block options.  The rest is very similar to doing this in Scratch 2. Moving ...