Arduino library for the LIS2MDL magnetometer with communication over SPI / I2C
- Heavily inspired by the SparkFun LSM6DS3 library
- Calibration code adapted from Kris Winer's library
#include <Arduino.h>
#include <LIS2MDL.h>
LIS2MDL mag;
float x, y, z;
void setup() {
Serial.begin(115200);
// configure the magnetometer
// settings below are default settings
mag.settings.tempCompensationEnabled = LIS2MDL_TEMP_COMPENSATION_ENABLED;
mag.settings.magSampleRate = LIS2MDL_MAG_ODR_10Hz;
// set up the wire interface
mag_status_t result = mag.begin();
if (result != MAG_SUCCESS)
Serial.println("Magnetometer Error");
else {
// probably a good idea to calibrate
Serial.println("Calibrating: move the magnetometer all around");
delay(4000);
mag.calibrate();
Serial.println("Calibration Complete");
}
}
void loop() {
x = mag.readFloatMagX();
y = mag.readFloatMagY();
z = mag.readFloatMagZ();
Serial.print("x: ");
Serial.print(x);
Serial.print(" y: ");
Serial.print(y);
Serial.print(" z: ");
Serial.println(z);
}
This code is released under the MIT License.