LIS3MDL magnetometer

The ST LIS3MDL reads the magnetic field on three axes over I2C at 0x1C, up to 6842 counts a gauss: the sensor of a digital compass.

Aliases: LIS3MDL compass, Adafruit LIS3MDL, Pololu LIS3MDL, three-axis magnetometer. Flat on the bench it reads the Earth's field: about 20 microtesla toward magnetic north and 45 down, at mid-northern latitudes. atan2 of the two horizontal readings is the heading.

Pins

Pin What it does
VIN, GND Supply, 3 to 5 V on the board.
SCL, SDA I2C. The board carries the pull-ups.
DRDY Low while a new sample waits.
INT The threshold interrupt, left high-Z by the model.

Properties

address is 0x1C or 0x1E. heading, pitch and roll are how the board sits; the sliders turn and tip it.

Reading it on an Arduino

With Adafruit's library, which Mokxi ships as Adafruit_LIS3MDL.h:

#include <Adafruit_LIS3MDL.h>
Adafruit_LIS3MDL lis3mdl;

void setup() {
  Serial.begin(9600);
  lis3mdl.begin_I2C();
}

void loop() {
  sensors_event_t event;
  lis3mdl.getEvent(&event);
  float heading = atan2(event.magnetic.y, event.magnetic.x) * 180 / PI;
  Serial.println(heading);
  delay(200);
}

How it talks

WHO_AM_I (0x0F) reads 0x3D. CTRL_REG1 (0x20) sets the data rate and performance mode, CTRL_REG2 (0x21) the range (4, 8, 12 or 16 gauss) and the soft reset, CTRL_REG3 (0x22) continuous, single or power-down (the reset). STATUS_REG (0x27) flags new data and the field is at 0x28 to 0x2D, low byte first. In I2C the address steps only when bit 7 of it is set, so a burst read starts at 0xA8.

What it does not model

The interrupt threshold, the self-test, offsets, noise, and nearby magnets.

Common mistakes

Reading zeros: it powers up powered down until continuous mode is written. A burst read from 0x28 without bit 7: the address does not step, and every byte is the same.