Thursday, 5 March 2026

Detecting and logging magnetism with a microbit

Producing a data logger using the microbit to detect and log changes in the magnetic field.

Traces

The micro:bit includes a built-in compass that can also be used as a magnetic field detector. With a small amount of code, we can use this sensor to measure changes in the magnetic field and log the data to a computer.

If you are new to this idea, a useful introduction is the video from Mr Morrison below, which explains the basic concept.





The video demonstrates how the micro:bit can detect magnetic fields and display the readings on the device itself. Let’s extend that idea by turning the micro:bit into a data logger that continuously records magnetic field changes.


Coding and Sending data to a Computer

Instead of displaying the magnetic readings directly on the micro:bit’s LEDs, we can send the data through the USB cable to a computer.

The MakeCode editor already provides blocks that allow data to be sent using the serial connection. By placing the magnetic measurement inside a command that continuously sends serial data, we can stream the readings to the computer.

In the example code, two values are transmitted:

  • X-axis magnetic field

  • Y-axis magnetic field

These correspond to two directions in which the magnetic field can change. Each measurement is sent repeatedly through the USB cable so the computer can record it.

From a coding perspective, this modification is very simple: instead of showing the value on the device, we send it through the serial interface.


Code needed


After downloading the program to the micro:bit, keep the USB cable connected, as this is how the data is transmitted.

Once the program starts running, the MakeCode interface should display a “Show Data Device” button similar to the one shown below.

On the Computer ready for data logging


Clicking this button opens a data viewer that shows the incoming magnetic readings in real time.

Data logging in action

Example: rocking the magnets
The graph above shows data recorded when a small set of circular magnets was rolled towards the micro:bit and then allowed to rock back and forth.

The rocking motion produces a clear oscillating pattern in both the X and Y magnetic field graphs. As the magnets move, the magnetic field detected by the sensor changes direction and strength, producing the wave-like traces you can see.

It’s a simple experiment, but it demonstrates how the micro:bit can be used as a low-cost scientific data logger for investigating magnetic fields and motion.








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

No comments:

Post a Comment

Detecting and logging magnetism with a microbit

Producing a data logger using the microbit to detect and log changes in the magnetic field. Traces The micro:bit includes a built-in compas...