Using the LSM303

Download the Library

To get started with the LSM303, first download and install the Adafruit_LSM303DLHC library from Github. Since this driver is part of the Adafruit Unified Sensor system, you will also need to download and install the Adafruit_Sensor library.

Basic Accelerometer Readings

The Adafruit_LSM303_Accel sensor class in the Adafruit_LSM303 library reports X, Y and Z axis accelerometer readings directly in meters per second squared. The AccelSensor example code in the library reads from the sensor and prints the acceleration readings to the Serial Monitor.

At rest, the sensor should report no acceleration except that due to gravity (about 9.8 meters/second squared). By calculating the angle of the gravity vector with respect to the X, Y and Z axis, the device can be used as an inclinometer.

Basic Magnetometer Readings

The Adafruit_LSM303_Mag sensor class in the Adafruit_LSM303 library reports X, Y and Z axis magnetometer readings directly in micro-Teslas. The MagSensor example code in the library reads from the sensor and prints the micro-Tesla readings to the Serial Monitor.

In the absence of any strong local magnetic fields, the sensor readings should reflect the magnetic field of the earth (between 20 and 60 micro-Teslas). When the sensor is held level, by calculating the angle of the magnetic filed with respect to the X and Y axis, the device can be used as a compass.

Computing a Compass Heading

To convert the microTesla readings into a 0-360 degree compass heading, we can use the atan2() function to compute the angle of the vector defined by the Y and X axis readings. The result will be in radians, so we multiply by 180 degrees and divide by Pi to convert that to degrees.

The following sketch will print the compass heading in degrees to to the serial monitor:
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_LSM303_U.h>

/* Assign a unique ID to this sensor at the same time */
Adafruit_LSM303_Mag_Unified mag = Adafruit_LSM303_Mag_Unified(12345);

void setup(void) 
{
  Serial.begin(9600);
  Serial.println("Magnetometer Test"); Serial.println("");
  
  /* Initialise the sensor */
  if(!mag.begin())
  {
    /* There was a problem detecting the LSM303 ... check your connections */
    Serial.println("Ooops, no LSM303 detected ... Check your wiring!");
    while(1);
  }
}

void loop(void) 
{
  /* Get a new sensor event */ 
  sensors_event_t event; 
  mag.getEvent(&event);
  
  float Pi = 3.14159;
  
  // Calculate the angle of the vector y,x
  float heading = (atan2(event.magnetic.y,event.magnetic.x) * 180) / Pi;
  
  // Normalize to 0-360
  if (heading < 0)
  {
    heading = 360 + heading;
  }
  Serial.print("Compass Heading: ");
  Serial.println(heading);
  delay(500);
}
Last updated on 2015-11-17 at 05.12.21 PM Published on 2013-03-10 at 07.00.43 PM