Use the micro:bit magnetometer with the Arduino IDE
Freescale’s MAG3110 is a small, low-power, digital 3-axis magnetometer. The device can be used in conjunction with a 3-axis accelerometer to realize an orientation independent electronic compass that can provide accurate heading information. It features a standard I2C serial interface output and smart embedded functions.
The MAG3110 is capable of measuring magnetic fields with an output data rate (ODR) up to 80 Hz; these output data rates correspond to sample intervals from 12.5 ms to several seconds. The MAG3110 is available in a plastic DFN package and it is guaranteed to operate over the extended temperature range of -40°C to +85°C.
You have a micro:bit so you already have one on the board
Code
You need to import the Sparkfun library for the MAG3110 to run this example – https://github.com/sparkfun/SparkFun_MAG3110_Breakout_Board_Arduino_Library/archive/master.zip
[codesyntax lang=”cpp”]
#include <SparkFun_MAG3110.h> MAG3110 mag = MAG3110(); void setup() { Serial.begin(9600); mag.initialize(); //Initializes the mag sensor mag.start(); //Puts the sensor in active mode } void loop() { int x, y, z; //Only read data when it's ready if(mag.dataReady()) { //Read the data mag.readMag(&x, &y, &z); Serial.print("X: "); Serial.print(x); Serial.print(", Y: "); Serial.print(y); Serial.print(", Z: "); Serial.println(z); Serial.println("--------"); delay(1000); } }
[/codesyntax]
Testing
Open the serial monitor and move your micro:bit through the various axis, you should see something like this
X: 218, Y: 65109, Z: 65274
——–
X: 71, Y: 64965, Z: 49
——–
X: 598, Y: 65036, Z: 248
——–
X: 423, Y: 65338, Z: 564
——–
X: 348, Y: 61, Z: 565
——–
X: 413, Y: 65532, Z: 576
——–
X: 502, Y: 65024, Z: 65352