Overview

The LSM303 breakout board combines a magnetometer/compass module with a triple-axis accelerometer to make a compact navigation subsystem. The I2C interface is compatible with both 3.3v and 5v processors and the two pins can be shared by other I2C devices. Combined with a 3-axis gyro such as the L3GD20, you have all the sensors you need for a complete IMU (Inertial Measurement Unit) for use in aerial, terrestrial or marine navigation.

In this tutorial we will show you how to connect the LSM303 to an Arduino and use it to measure orientation relative to the earth's magnetic field, and acceleration in three axis.

How it Works:

MEMS - Micro Electro-Mechanical Systems

The sensor consists of micro-machined structures on a silicon wafer. There are structures designed to measure acceleration and magnetic fields in the X, Y and Z axis.

Acceleration Measurement

These structures are suspended by polysilicon springs which allow them to deflect when subject to acceleration in the X, Y and/or Z axis. Deflection causes a change in capacitance between fixed plates and plates attached to the suspended structure. This change in capacitance on each axis is converted to an output voltage proportional to the acceleration on that axis.

Magnetic Field Measurement

These structures are similar to the accelerometer structures, but are etched with microscopic coils. An excitation current is passed through the coils, and the Lorentz Force due to the magnetic field causes the structure to deflect. Once again the deflection is converted to an output voltage proportional to the strength of the magnetic field in that axis.

Assembly and Wiring

Board Assembly:

All surface mount components are pre-soldered to the board. You can solder connections directly to the board, or you can install the header strip (provided) to simplify use in a breadboard.

Position the header

Cut the header to length if necessary and insert - long pins down - into a breadboard.

Position the board

Place the board on top of the header pins. Prop the back-side up of necessary to level the board before soldering.

And Solder!

Solder each pin to assure a good electrical connection.

If you are new to soldering, check out our Guide to Excellent Soldering.

Connect to the Arduino:

The LSM303 breakout requires only 4 wires:
  • GND->GND
  • VIN->5v (It will also work on 3.3v)
  • SDA->SDA (A4 on 'classic' Arduinos)
  • SCL->SCL (A5 on 'classic' Arduinos)

Arduino Code

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:
Download: file
#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);
}

Python & CircuitPython

It's easy to use the LSM303 sensor with CircuitPython and the Adafruit CircuitPython LSM303 module.  This module allows you to easily write Python code that reads the accelerometer and magentometer from the sensor.

You can use this sensor with any CircuitPython microcontroller board or with a computer that has GPIO and Python thanks to Adafruit_Blinka, our CircuitPython-for-Python compatibility library.

CircuitPython Microcontroller Wiring

First wire up a LSM303 to your board exactly as shown on the previous pages for Arduino using an I2C connection.  Here's an example of wiring a Feather M0 to the sensor with I2C:

  • Board 3V to sensor VIN
  • Board GND to sensor GND
  • Board SCL to sensor SCL
  • Board SDA to sensor SDA

Python Computer Wiring

Since there's dozens of Linux computers/boards you can use we will show wiring for Raspberry Pi. For other platforms, please visit the guide for CircuitPython on Linux to see whether your platform is supported

Here's the Raspberry Pi wired with I2C:

  • Pi 3V3 to sensor VIN
  • Pi GND to sensor GND
  • Pi SCL to sensor SCL
  • Pi SDA to sensor SDA

CircuitPython Installation of LSM303 Library

Next you'll need to install the Adafruit CircuitPython LSM303 library on your CircuitPython board.  

First make sure you are running the latest version of Adafruit CircuitPython for your board.

Next you'll need to install the necessary libraries to use the hardware--carefully follow the steps to find and install these libraries from Adafruit's CircuitPython library bundle.  Our introduction guide has a great page on how to install the library bundle for both express and non-express boards.

Remember for non-express boards like the, you'll need to manually install the necessary libraries from the bundle:

  • adafruit_lsm303.mpy
  • adafruit_bus_device

Before continuing make sure your board's lib folder or root filesystem has the adafruit_lsm303.mpy, and adafruit_bus_device files and folders copied over.

Next connect to the board's serial REPL so you are at the CircuitPython >>> prompt.

CircuitPython & Python Usage

To demonstrate the usage of the sensor we'll initialize it and read the accelerometer and compass/magnetometer from the board's Python REPL.

Run the following code to import the necessary modules and initialize the I2C connection with the sensor:

Download: file
import board
import busio
import adafruit_lsm303
i2c = busio.I2C(board.SCL, board.SDA)
sensor = adafruit_lsm303.LSM303(i2c)

Now you're ready to read values from the sensor using any of these properties:

  • acceleration - A 3-tuple of X, Y, Z acceleration values in meters per second per second (m/s^2).
  • raw_acceleration - A 3-tuple of X, Y, Z acceleration values in the raw 16-bit unsigned values returned by the sensor.  This is handy for doing the most accurate math yourself, but in practice you probably want to use the acceleration attribute above instead!
  • magnetic - A 3-tuple of the X, Y, Z magnetometer readings in micro-Teslas.
Download: file
print('Acceleration (m/s^2): X={0:0.3f} Y={1:0.3f} Z={2:0.3f}'.format(*sensor.acceleration))
print('Magnetometer (micro-Teslas): X={0:0.3f} Y={1:0.3f} Z={2:0.3f}'.format(*sensor.magnetic))

In addition you can read and write a few properties to adjust the magnetometer:

  • mag_gain - The gain of the magnetometer, should be a value of:
    • adafruit_lsm303.MAGGAIN_1_3 - 1.3x (the default)
    • adafruit_lsm303.MAGGAIN_1_9 - 1.9x
    • adafruit_lsm303.MAGGAIN_2_5 - 2.5x
    • adafruit_lsm303.MAGGAIN_4_0 - 4.0x
    • adafruit_lsm303.MAGGAIN_4_7 - 4.7x
    • adafruit_lsm303.MAGGAIN_5_6 - 5.6x
    • adafruit_lsm303.MAGGAIN_8_1 - 8.1x
  • mag_rate - The rate at which the magnetometer is sampled, should be a value of:
    • adafruit_lsm303.MAGRATE_0_7 - 0.75 hz (the default)
    • adafruit_lsm303.MAGRATE_1_5 - 1.5 hz
    • adafruit_lsm303.MAGRATE_3_0 - 3 hz
    • adafruit_lsm303.MAGRATE_7_5 - 7.5 hz
    • adafruit_lsm303.MAGRATE_15 - 15 hz
    • adafruit_lsm303.MAGRATE_30 - 30 hz
    • adafruit_lsm303.MAGRATE_75 - 75 hz
    • adafruit_lsm303.MAGRATE_220 - 220 hz
Download: file
sensor.mag_gain = adafruit_lsm303.MAGGAIN_8_1
sensor.mag_rate = adafruit_lsm303.MAGRATE_220

That's all there is to using the LSM303 with CircuitPython!

Below is a complete example of reading the sensor and printing its values every second.  Save this as code.py on your board and open the REPL to see the output.

Full Example Code

""" Display both accelerometer and magnetometer data once per second """

import time
import board
import busio
import adafruit_lsm303

i2c = busio.I2C(board.SCL, board.SDA)
sensor = adafruit_lsm303.LSM303(i2c)

while True:
    acc_x, acc_y, acc_z = sensor.acceleration
    mag_x, mag_y, mag_z = sensor.magnetic

    print('Acceleration (m/s^2): ({0:10.3f}, {1:10.3f}, {2:10.3f})'.format(acc_x, acc_y, acc_z))
    print('Magnetometer (gauss): ({0:10.3f}, {1:10.3f}, {2:10.3f})'.format(mag_x, mag_y, mag_z))
    print('')
    time.sleep(1.0)

Calibration

(Calibration GUI image by Fabio Varesano)


The LSM303 chips are factory calibrated to a level of accuracy sufficient for many purposes. But for ultra-critical applications such as an IMU, you may want to further calibrate the device.

Ultimate Calibration:

For super-precise accelerometer calibration, you will want to check out the FreeIMU Magnetometer and Accelerometer GUI by the late Fabio Varesano. The image above (from Fabio's site) shows a graphical representation of the sensor readings and the resulting calibration offsets calculated from the raw data.

This comprehensive calibration suite is designed to run on a PC. It is much too large to run on a microcontroller, like the Arduino, but the resulting calibration offsets it generates can be incorporated into your Arduino sketch for better accuracy.

Simplified Calibration:

A simpler method that still generates good results can be accomplished on the Arduino. This method uses a simple sketch to record the minimum and maximum readings on all 3 axis. While running the sketch, slowly rotate the LSM303 module multiple times in all three axis. The object is to record the absolute minimums and maximums for each axis, so the more you rotate it, the more likely you are to capture the absolute peak.

Be sure to rotate the sensor slowly about its center so that the accelerometer readings will represent just acceleration due to gravity and not linear acceleration of the sensor due to movement. After a while, the sketch output will stabilize. The values displayed will be the the min and max ranges for each axis and can be used to re-scale the output of the sensor.

The values obtained via the calibration sketch can be used to perform a 2-point calibration on each of the 3 axis:  Two Point Calibration

Calibration Sketch:

Download: file
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_LSM303_U.h>

/* Assign a unique ID to these sensors */
Adafruit_LSM303_Accel_Unified accel = Adafruit_LSM303_Accel_Unified(54321);
Adafruit_LSM303_Mag_Unified mag = Adafruit_LSM303_Mag_Unified(12345);

float AccelMinX, AccelMaxX;
float AccelMinY, AccelMaxY;
float AccelMinZ, AccelMaxZ;

float MagMinX, MagMaxX;
float MagMinY, MagMaxY;
float MagMinZ, MagMaxZ;

long lastDisplayTime;

void setup(void) 
{
  Serial.begin(9600);
  Serial.println("LSM303 Calibration"); Serial.println("");
  
  /* Initialise the accelerometer */
  if(!accel.begin())
  {
    /* There was a problem detecting the ADXL345 ... check your connections */
    Serial.println("Ooops, no LSM303 detected ... Check your wiring!");
    while(1);
  }
  /* Initialise the magnetometer */
  if(!mag.begin())
  {
    /* There was a problem detecting the LSM303 ... check your connections */
    Serial.println("Ooops, no LSM303 detected ... Check your wiring!");
    while(1);
  }
  lastDisplayTime = millis();
}

void loop(void) 
{
  /* Get a new sensor event */ 
  sensors_event_t accelEvent; 
  sensors_event_t magEvent; 
  
  accel.getEvent(&accelEvent);
  mag.getEvent(&magEvent);
  
  if (accelEvent.acceleration.x < AccelMinX) AccelMinX = accelEvent.acceleration.x;
  if (accelEvent.acceleration.x > AccelMaxX) AccelMaxX = accelEvent.acceleration.x;
  
  if (accelEvent.acceleration.y < AccelMinY) AccelMinY = accelEvent.acceleration.y;
  if (accelEvent.acceleration.y > AccelMaxY) AccelMaxY = accelEvent.acceleration.y;

  if (accelEvent.acceleration.z < AccelMinZ) AccelMinZ = accelEvent.acceleration.z;
  if (accelEvent.acceleration.z > AccelMaxZ) AccelMaxZ = accelEvent.acceleration.z;

  if (magEvent.magnetic.x < MagMinX) MagMinX = magEvent.magnetic.x;
  if (magEvent.magnetic.x > MagMaxX) MagMaxX = magEvent.magnetic.x;
  
  if (magEvent.magnetic.y < MagMinY) MagMinY = magEvent.magnetic.y;
  if (magEvent.magnetic.y > MagMaxY) MagMaxY = magEvent.magnetic.y;

  if (magEvent.magnetic.z < MagMinZ) MagMinZ = magEvent.magnetic.z;
  if (magEvent.magnetic.z > MagMaxZ) MagMaxZ = magEvent.magnetic.z;

  if ((millis() - lastDisplayTime) > 1000)  // display once/second
  {
    Serial.print("Accel Minimums: "); Serial.print(AccelMinX); Serial.print("  ");Serial.print(AccelMinY); Serial.print("  "); Serial.print(AccelMinZ); Serial.println();
    Serial.print("Accel Maximums: "); Serial.print(AccelMaxX); Serial.print("  ");Serial.print(AccelMaxY); Serial.print("  "); Serial.print(AccelMaxZ); Serial.println();
    Serial.print("Mag Minimums: "); Serial.print(MagMinX); Serial.print("  ");Serial.print(MagMinY); Serial.print("  "); Serial.print(MagMinZ); Serial.println();
    Serial.print("Mag Maximums: "); Serial.print(MagMaxX); Serial.print("  ");Serial.print(MagMaxY); Serial.print("  "); Serial.print(MagMaxZ); Serial.println(); Serial.println();
    lastDisplayTime = millis();
  }
}

Chris H's Calibration

A fellow maker in the Adafruit forum writes:

After many hours, I have finally been able to get the LSM303DLHC to give me good tilt compensated heading. I will try to attach the sketch to this post.

Download: file
/*
 *  This is a single sketch for tilt compensated compass using an LSM303DLHC.
 *  It does not use any libraries, other than wire, because I found a number of
 *  errors in libraries that are out there.The biggest problem is with libraries
 *  that rely on the application note for the lsm303.  That application note seems to
 *  include assumptions that are wrong, and I was not able to get it to produce
 *  reliable tilt compensated heading values.  If you look at how pitch, roll and heading
 *  are calculated below, you will see that the formula have some of the factors from
 *  the application note, but other factors are not included. 
 * 
 *  Somehow the matrix manupulations that are described in the application note
 *  introduce extra factors that are wrong.  For example, the pitch and roll calculation should
 *  not depend on whether you rotate pitch before roll, or vice versa. But if you
 *  go through the math using the application note, you will find that they give
 *  different formula 
 * 
 *  Same with Heading.  When I run this sketch on my Adafruit break-out board, I get very
 *  stable pitch, roll and heading, and the heading is very nicely tilt compensated, regardless
 *  of pitch or roll. 
 */
int ACC_Data0, ACC_Data1, ACC_Data2, ACC_Data3, ACC_Data4, ACC_Data5;

int MAG_Data0, MAG_Data1, MAG_Data2, MAG_Data3, MAG_Data4, MAG_Data5;

int Ax, Ay, Az, Mx, My, Mz;

float Xm_print, Ym_print, Zm_print;
float Xm_off, Ym_off, Zm_off, Xm_cal, Ym_cal, Zm_cal, Norm_m;

float Xa_print, Ya_print, Za_print;
float Xa_off, Ya_off, Za_off, Xa_cal, Ya_cal, Za_cal, Norm_a;

const float alpha = 0.15;
float fXa = 0;
float fYa = 0;
float fZa = 0;
float fXm = 0;
float fYm = 0;
float fZm = 0;
float pitch, pitch_print, roll, roll_print, Heading;
float fXm_comp, fYm_comp;


#include <Wire.h>

void setup() {

  Wire.begin();
  Serial.begin(9600);
 
  Wire.beginTransmission(0x19); // Set accel
  Wire.write(0x20);             // CTRL_REG1_A register
  Wire.write(0x47);             // 50 Hz, normal power, all 3 axis enabled
  Wire.endTransmission();

  Wire.beginTransmission(0x19); // Set accel
  Wire.write(0x23);             // CTRL_REG4_A register
  Wire.write(0x08);             // continuous update, littleendian, 2g, high resolution, 4-wire spi
  Wire.endTransmission();

  Wire.beginTransmission(0x1E); // set Mag
  Wire.write(0x00);             // CRA_REG_M register
  Wire.write(0x14);             // 30 Hz min data output rate
  Wire.endTransmission();

  Wire.beginTransmission(0x1E); // Set Mag
  Wire.write(0x02);             // MR_REG_M
  Wire.write(0x00);             // continuous conversion mode
  Wire.endTransmission();
 

}

void loop() {
  Wire.beginTransmission(0x19);
  Wire.write(0x28);
  Wire.endTransmission();
  Wire.requestFrom(0x19, (byte)1);
  ACC_Data0 = Wire.read();
 
  Wire.beginTransmission(0x19);
  Wire.write(0x29);
  Wire.endTransmission();
  Wire.requestFrom(0x19, (byte)1);
  ACC_Data1 = Wire.read();

  Wire.beginTransmission(0x19);
  Wire.write(0x2A);
  Wire.endTransmission();
  Wire.requestFrom(0x19, (byte)1);
  ACC_Data2 = Wire.read();
 
  Wire.beginTransmission(0x19);
  Wire.write(0x2B);
  Wire.endTransmission();
  Wire.requestFrom(0x19, (byte)1);
  ACC_Data3 = Wire.read();

  Wire.beginTransmission(0x19);
  Wire.write(0x2C);
  Wire.endTransmission();
  Wire.requestFrom(0x19, (byte)1); 
  ACC_Data4 = Wire.read();
 
  Wire.beginTransmission(0x19);
  Wire.write(0x2D);
  Wire.endTransmission();
  Wire.requestFrom(0x19, (byte)1);
  ACC_Data5 = Wire.read();

  Ax = (int16_t)(ACC_Data1 << 8) | ACC_Data0;
  Ay = (int16_t)(ACC_Data3 << 8) | ACC_Data2;
  Az = (int16_t)(ACC_Data5 << 8) | ACC_Data4;

  Xa_off = Ax/16.0 + 14.510699; // add/subtract bias calculated by Magneto 1.2. Search the web and you will
  Ya_off = Ay/16.0 - 17.648453; // find this Windows application.  It works very well to find calibrations
  Za_off = Az/16.0 -  6.134981;
  Xa_cal =  1.006480*Xa_off - 0.012172*Ya_off + 0.002273*Za_off; // apply scale factors calculated by Magneto1.2
  Ya_cal = -0.012172*Xa_off + 0.963586*Ya_off - 0.006436*Za_off;
  Za_cal =  0.002273*Xa_off - 0.006436*Ya_off + 0.965482*Za_off;
  Norm_a = sqrt(Xa_cal * Xa_cal + Ya_cal * Ya_cal + Za_cal * Za_cal); //original code did not appear to normalize, and this seems to help
  Xa_cal = Xa_cal / Norm_a;
  Ya_cal = Ya_cal / Norm_a;
  Za_cal = Za_cal / Norm_a;

  Ya_cal = -1.0 * Ya_cal;  // This sign inversion is needed because the chip has +Z up, while algorithms assume +Z down
  Za_cal = -1.0 * Za_cal;  // This sign inversion is needed for the same reason and to preserve right hand rotation system

// Low-Pass filter accelerometer
  fXa = Xa_cal * alpha + (fXa * (1.0 - alpha));
  fYa = Ya_cal * alpha + (fYa * (1.0 - alpha));
  fZa = Za_cal * alpha + (fZa * (1.0 - alpha));


  Wire.beginTransmission(0x1E);
  Wire.write(0x03);
  Wire.endTransmission();

  Wire.requestFrom(0x1E, (byte)6);
  MAG_Data0 = Wire.read();
  MAG_Data1 = Wire.read();
  MAG_Data2 = Wire.read();
  MAG_Data3 = Wire.read();
  MAG_Data4 = Wire.read();
  MAG_Data5 = Wire.read();

  Mx = (int16_t)(MAG_Data0 << 8) | MAG_Data1;
  Mz = (int16_t)(MAG_Data2 << 8) | MAG_Data3;
  My = (int16_t)(MAG_Data4 << 8) | MAG_Data5;

  Xm_off = Mx*(100000.0/1100.0) -   617.106577; // Gain X [LSB/Gauss] for selected sensor input field range (1.3 in these case)
  Ym_off = My*(100000.0/1100.0) -  3724.617984; // Gain Y [LSB/Gauss] for selected sensor input field range
  Zm_off = Mz*(100000.0/980.0 ) - 16432.772031;  // Gain Z [LSB/Gauss] for selected sensor input field range
  Xm_cal =  0.982945*Xm_off + 0.012083*Ym_off + 0.014055*Zm_off; // same calibration program used for mag as accel.
  Ym_cal =  0.012083*Xm_off + 0.964757*Ym_off - 0.001436*Zm_off;
  Zm_cal =  0.014055*Xm_off - 0.001436*Ym_off + 0.952889*Zm_off;
  Norm_m = sqrt(Xm_cal * Xm_cal + Ym_cal * Ym_cal + Zm_cal * Zm_cal); // original code did not appear to normalize  This seems to help
  Xm_cal = Xm_cal / Norm_m;
  Ym_cal = Ym_cal / Norm_m;
  Zm_cal = Zm_cal / Norm_m;
 
  Ym_cal = -1.0 * Ym_cal;  // This sign inversion is needed because the chip has +Z up, while algorithms assume +Z down
  Zm_cal = -1.0 * Zm_cal;  // This sign inversion is needed for the same reason and to preserve right hand rotation system

// Low-Pass filter magnetometer
  fXm = Xm_cal * alpha + (fXm * (1.0 - alpha));
  fYm = Ym_cal * alpha + (fYm * (1.0 - alpha));
  fZm = Zm_cal * alpha + (fZm * (1.0 - alpha));


// Pitch and roll
  pitch = asin(fXa);
  roll = -asin(fYa);
  pitch_print = pitch*180.0/M_PI;
  roll_print = roll*180.0/M_PI;

// Tilt compensated magnetic sensor measurements
  fXm_comp = fXm*cos(pitch) + fZm*sin(pitch);
  fYm_comp = fYm*cos(roll) - fZm*sin(roll);

  Heading = (atan2(-fYm_comp,fXm_comp)*180.0)/M_PI;

  if (Heading < 0)
  Heading += 360;

  Serial.print("Pitch (X): "); Serial.print(pitch_print); Serial.print("  ");
  Serial.print("Roll (Y): "); Serial.print(roll_print); Serial.print("  ");
  Serial.print("Heading: "); Serial.println(Heading);

  delay(250);

}

Making Tracks!

Now let's use the LSM303 module to do some simple navigation!
One day, making tracks
In the prairie of Prax,
Came a North-Going Zax
And a South-Going Zax.
This Zax-O-Meter is the perfect navigation instrument for either a North or a South-going Zax. This project demonstrates how to use the LSM303 magnetometer output to implement a simple navigation system. No matter which way you turn, the pointer will always rotate to the desired direction of travel.
Never budge! That’s my rule.
Never budge in the least!
Not an inch to the west!
Not an inch to the east!
The Zax-O-Meter uses the computed compass heading as feedback to a continuous rotation servo. When the compass heading is zero degrees (due north), the servo stops rotating. Any deviation from that value causes the servo to rotate in the opposite direction to compensate. This basic principle of negative feedback can be used to build a navigation system for an autonomous robot.

Materials:

To build the Zax-O-Meter, you will need:

Calibrate your servo:

For the Zax-O-Meter to function accurately, you first need to find the 'neutral' point of your continuous rotation servo. That is the servo output value that results in minimum rotation. This value is typically about 90, but varies somewhat between servos. Run this sketch and modify the value until you get minimum rotation. That is the value you should use for ServoNeutral in the Zax-O-Meter sketch.
Download: file
#include <Servo.h> 
Servo servo;  

void setup() 
{ 
  servo.attach(9);  // attaches the servo on pin 9 to the servo object 
  servo.write(90);  // change this value to achieve minimum rotation!
} 
 
void loop() 
{ 
} 

Mount the servo

Mark and widen the opening in the enclosure to fit the servo. Insert the servo with the rotor toward the center of the enclosure. Press down until the flanges are flush with the surface, the servo should snap into place and be held securely.

Mount the Uno and wire it up

Mount the Uno in the enclosure with the supplied screws. Wire the servo and sensor as follows:

Servo:
  • Black -> Gnd
  • Red -> 5v
  • White -> Digital Pin 9

LSM303:
  • Gnd -> Gnd
  • Vin -> 3.3v
  • SDA -> Analog 4
  • SCL -> Analog 5
Then route the sensor wire through the opening next to the servo and close up the enclosure.

Add a pointer

Cut a pointer from some stiff cardboard or foam-core and attach it to the servo horn with some double-sided foam tape.

Attach the sensor to the underside of the arrow with some more double-sided foam tape. Locate the sensor as far away from the servo body as possible to avoid magnetic interference from the motor.

Add Zaxen!

Find an image of your favorite Zax. Use Paint or other image editing tool to make a mirror image pair.

Print the image on some heavy card-stock and fold it over to make a double-sided image.

Cut it out and mount to the top of your indicator arrow with some double-sided tape.

Code:

Load the code below. Don't forget to change "ServoNeutral" to the neutral value from the Servo Calibration step.

The example code is for a North-going Zax and uses a targetHeading of 0. If you are a Zax of the South-going persuasion, a targetHeading of 180 will keep you in your South-going groove. For those with a rebellious streak, choose any targetHeading setting from 0 - 360 degrees and start making tracks in the heading of your choice!
Download: file
// **********************************************
// Zax-O-Meter Sketch 
// for the Adafruit LSM303 Magnetometer Breakout
//
// Written by Bill Earl for Adafruit Industries
//
// **********************************************

#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_LSM303_U.h>
#include <Servo.h>

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

// This is our continuous rotation servo
Servo servo;

// Pi for calculations - not the raspberry type
const float Pi = 3.14159;

// This is the value that gives you minimal rotation on
// a continuous rotation servo.  It is usually about 90.
// adjust this value to give minimal rotation for your servo
const float ServoNeutral = 97;  

// This is the desired direction of travel
// expressed as a 0-360 degree compass heading
// 0.0 = North
// 90.0 = East
// 180.0 = South
// 270 = West
const float targetHeading = 0.0;


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);
  }
  
  servo.attach(9);  // Attach servo to pin 9
}

void loop(void) 
{
  /* Get a new sensor event */ 
  sensors_event_t event; 
  mag.getEvent(&event);
     
  // 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;
  }
  
  // Calculate the error between tha measured heading and the target heading.
  float error = heading - targetHeading;
  if (error > 180)
  {
    error = error - 360;  // for angles > 180, correct in the opposite direction.
  }
  // A non-zero difference between the heading and the 
  // targetHeading will bias the servoNeutral value and 
  // cause the servo to rotate back toward the targetHeading.
  // The divisor is to reduce the reaction speed and avoid oscillations
  servo.write(ServoNeutral + error / 4 );

  delay(40);
}

Downloads and Links

This guide was first published on Mar 10, 2013. It was last updated on Mar 10, 2013.