LSM303AGR accelerometer and compass

The ST LSM303AGR puts an accelerometer at 0x19 and a magnetometer at 0x1E in one package, the two halves of a tilt-compensated compass.

Aliases: LSM303, LSM303DLHC, eCompass, Adafruit LSM303AGR. The accelerometer says which way is down, the magnetometer which way is north, and together they give a heading that stays right when the board tips.

Pins

Pin What it does
VIN, GND Supply, 3 to 5 V on the board.
SCL, SDA I2C, both halves on the same bus. The board carries the pull-ups.
INT1, INT2 Interrupts, left high-Z by the model.

Properties

heading, pitch and roll are how the board sits; the sliders turn and tip it.

Reading it on an Arduino

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

#include <Adafruit_LSM303_Accel.h>
Adafruit_LSM303_Accel_Unified accel(54321);

void setup() {
  Serial.begin(9600);
  accel.begin();
  accel.setRange(LSM303_RANGE_4G);
}

void loop() {
  sensors_event_t event;
  accel.getEvent(&event);
  Serial.println(event.acceleration.z);
  delay(200);
}

How it talks

The accelerometer: WHO_AM_I_A (0x0F) reads 0x33; CTRL_REG1_A (0x20) sets the data rate (off at reset) and the axes; CTRL_REG4_A (0x23) the range and high resolution. Its outputs at 0x28 are left-justified: 12, 10 or 8 bits by the mode. The address steps only with bit 7 set. The magnetometer: WHO_AM_I_M (0x4F) reads 0x40; CFG_REG_A_M (0x60) sets continuous, single or idle (the reset) and the rate; the field is at 0x68, 1.5 milligauss a count.

What it does not model

The FIFO, the click and interrupt engines, the temperature sensor, hard-iron offsets, and noise.

Common mistakes

Reading the accelerometer as right-justified: shift the sixteen-bit value down by 4, 6 or 8 for the mode first.