Lesson 7: 9-DOF Sensor


The 9-DOF (9 Degrees of Freedom) sensor is a sensor breakout board that allows for capturing 9 distinct types of motion and orientation:

  • 3 degrees of acceleration (accelerometer)
  • 3 degrees of magnetic orientation (magnetometer)
  • 3 degrees of angular velocity (gyroscope)

9-DOF Sensor

The 9-DOF sensor from Adafruit uses 2 sensors:

  1. LSM303DLHC – a 3-axis accelerometer (up to +/- 16g) and 3-axis magnetometer (up to +/- 8.1 gauss)
  2. L3GD20 – a 3-axis gyroscope (up to +/- 2000 dps)

In this project, we will only be using the 3-axis magnetometer for calculating and sensing the current heading of our rover.

To connect the 9-DOF sensor, it uses the I2C interface to talk to the Arduino, rather than the standard digital I/O pins we normally use for LEDs and Servos. Using the I2C chips, we only need 4 wires to connect to the Arduino.

  • GND connects to the GND pin on the Arduino UNO
  • VIN connects to the 5V pin on the Arduino UNO
  • SCL connects to the Analog A5 pin on the Arduino UNO
  • SDA connects to the Analog A4 pin on the Arduino UNO


Software Libraries and Drivers

In order to use the 9DOF sensor in your Arduino code, the following libraries must be available:

  • Adafruit Unified Sensor library
  • LSM303DLHC library
  • L3GD20 library
  • Adafruit 9DOF library

These software libraries contain the drivers and necessary helper functions needed to access the data from the sensor.

Sample Code

#include <Wire.h>
#include <Adafruit_Sensor.h> // Adafruit Sensor library
#include <Adafruit_LSM303_U.h> // Magnetometer library
#include <Adafruit_L3GD20_U.h> // Gyroscope library
#include <Adafruit_9DOF.h> // 9-DOF library

// Define sensors
Adafruit_9DOF dof = Adafruit_9DOF();
Adafruit_LSM303_Mag_Unified mag = Adafruit_LSM303_Mag_Unified(12345);

// Sensor event vectors
sensors_event_t magEvent;
sensors_vec_t orientation;

void setup() {
Serial.begin(9600); // open serial port for debugging

if (!mag.begin()) {
Serial.println(“LSM303 magnetometer not found…”);
while(1); // We cannot do anything without the sensor

void loop() {
if (dof.magGetOrientation(SENSOR_AXIS_Z, &magEvent, &orientation))
Serial.print("Heading: ");
Serial.println(" degrees");
delay(100); // delay for 100ms before starting again