The micro:bit's built-in magnetometer chip is intended for use as compass to detect magnetic north. Like the compass app on your phone, this requires calibration and in my experience doesn't work very reliably. However, it is great for detecting the presence of a magnet!

Magnet Detector

The following project will make the micro:bit's display show a cross when a magnet comes near. This works best with a strong 'neodymium' magnet like the one in the side panel.

Angled shot of a High-strength 'rare earth' magnet.
Yow! These things are super powerful. 1/2" diameter, 3/16" thick discs, south side is marked with a red line. Great for use with your SpokePOV Kit. If you have an aluminium...
$2.50
In Stock

When you are looking at the top of the micro:bit, the compass chip is more or less behind button B. 

Note that I have had problems with this project using battery power from the battery connector. However, its fine powered from a USB lead.

JavaScript Block Code

When the program starts the micro:bit will automatically take you through a calibration process for the compass chip. This involves tilting the micro:bit around in a circular motion in order to light up a ring of LEDs on the display. 

The JavaScript Blocks Code editor is embedded directly on this page below. From the editor, you can click on Download button (bottom right) and then copy the downloaded file onto your micro:bit. Alternatively, you can Click here to open the editor in a separate browser tab.

In this program the block magnetic force is used to measure the intensity of the magnetic field near the compass chip on your micro:bit. This is used in the on start block to establish a baseline reading of magnetic strength with no magnet near the micro:bit. This happens when the micro:bit is first powered up or the reset button is pressed.

The forever loop repeatedly takes readings and checks to see if the absolute value of the difference between the new reading and the baseline reading is above 100 and if it is it displays the cross symbol on the display. The absolute value is just the value with the sign removed. This is necessary because, depending on which pole of the magnet is pointing towards the compass chip, the magnetic force reading may decrease rather than increase.

You may need to increase the threshold of 100 if the cross appears even without a magnet being near.

MicroPython

To run the MicroPython version of the code, open up the online Python editor here and paste the following code into the editor window.

from microbit import *

baseline = compass.get_field_strength() # Take a baseline reading of magnetic strength

while True:
  if abs(compass.get_field_strength() - baseline) > 10000:
      # Magnetic field strength increased by 10000
      display.show(Image.NO)    # Show a cross symbol
  else:
      display.clear()

The program first imports the microbit library that contains the compass and display objects needed in the program.

The while loop works just like its JavaScript Blocks sibling. It repeatedly takes readings and checks to see if the absolute value of the difference between the new reading and the baseline reading is above 10000 and if it is it displays the cross symbol on the display. The abs value is just the value with the sign removed. This is necessary because, depending on which pole of the magnet is pointing towards the compass chip, the magnetic force reading may decrease rather than increase.

You may need to increase the threshold of 10000 if the cross appears even without a magnet being near.

Arduino

Make sure that you have your Arduino environment set up for micro:bit by following this guide.

Now start a new Sketch by clicking on the File menu and New. Then paste the following code into the editor window.

#include "Wire.h"
#include <SparkFun_MAG3110.h>
#include <Adafruit_Microbit.h>

Adafruit_Microbit_Matrix microbit;
MAG3110 compass = MAG3110();  // The compass chip
int baseline = 0;             

void setup() {
  microbit.begin();
  compass.initialize();       // Initializes the compass chip
  compass.start();            // Puts the sensor in active mode
  baseline = readStrength();  // Take a baseline reading of magnetic strength
  delay(500);

}

void loop() {
  if (abs(readStrength() - baseline) > 15000) {
    // Magnetic field strength increased by 15000
    microbit.show(microbit.NO);
  }
  else {
    microbit.clear();
  }
}

int readStrength() {
  int x, y, z;
  while(!compass.dataReady()) {};   // Wait for data to become available to read
  compass.readMag(&x, &y, &z);      // Read data into variables
  // calculate the RMS power combining x, y and z readings
  int power = sqrt((sq(float(x)) + sq(float(y)) + sq(float(z))) / 3);
  return power;
}
If you get an error such as: fatal error: ble_gatts.h: No such file or directory when you go to upload, then make sure you have selected a Soft Device of S110 from the Arduino Tools menu.

The Arduino version of the compass library does not include an equivalent to the magnetic force block of the Blocks editor or the get_field_strength of MicroPython. This means that we have to write our own, called readStrength. This takes the x, y and z readings from the compass chip and combines them using a mathematical technique called RMS (root mean square). That takes a kind of average of the readings.

You may need to increase the threshold of 15000 if the cross appears even without a magnet being near.

This guide was first published on Mar 02, 2018. It was last updated on Mar 02, 2018.

This page (Magnetometer) was last updated on Jan 15, 2018.

Text editor powered by tinymce.