# LSM303 Accelerometer + Compass Breakout

## Overview

![](https://cdn-learn.adafruit.com/assets/assets/000/083/254/medium800/sensors_compass.jpg?1572391355)

The [LSM303](http://www.adafruit.com/products/4413 "Link: http://www.adafruit.com/products/4413") 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](http://www.adafruit.com/products/1032 "Link: http://www.adafruit.com/products/1032"), 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, CircuitPython board, or Blinka supported device, and how to use it to measure orientation relative to the earth's magnetic field, and acceleration in three axis.

![](https://cdn-learn.adafruit.com/assets/assets/000/083/729/medium800/sensors_iso_shot_crop.jpg?1573071913)

One great feature of the newer LSM303AGR is that it includes a **[STEMMA QT](https://learn.adafruit.com/introducing-adafruit-stemma-qt)&nbsp;**connectors that allow you to use it&nbsp;_without soldering._ Just plug in a [STEMMA QT to male header cable](https://www.adafruit.com/product/4209) to connect it to a breadboard or development board with female headers and you're off to the races! You can even chain it with other STEMMA QT breakouts using a [STEMMA QT cable](https://www.adafruit.com/product/4210)

![](https://cdn-learn.adafruit.com/assets/assets/000/083/732/medium800/sensors_top_stemma.jpg?1573072339)

## 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](http://en.wikipedia.org/wiki/Lorentz_force "Link: http://en.wikipedia.org/wiki/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.

# LSM303 Accelerometer + Compass Breakout

## Which LSM303 Do I Have?

There are now two Adafruit made LSM303 breakouts! Schnikes! They are nearly identical in function but different enough that they require different drivers for the magnetometer. Why only the magnetometer? Well, I'm gonna let you in on a little secret: the LSM303 is two sensors stuck in the same box!&nbsp;

Because both packages have the same accelerometer sensor with the same register layout, we can use the same accelerometer driver for both. The magnetometers _despite both having the same I2C address_ (0x1E), have completely different register layouts which means they each need their own driver library.

So, you're going to need to know which version you have. Here is a highly scientific way of telling the two _ **Adafruit** _ breakouts apart:

**The LSM303AGR IS BLACK AND SAYS "LSM303AGR" unlike the  
LSM303DLHC WHICH IS BLUE AND SAYS "LSM303DLHC"**

Complex, I know, but I believe in you. There are more subtle differences outlined below

# LSM303AGR

The new kid on the adafruit block is the LSM303AGR. It's an update to the LSM303 series that is _much_ smaller and has a different magnetometer chip inside. Our breakout looks like this:

![](https://cdn-learn.adafruit.com/assets/assets/000/083/723/medium800/sensors_top_crop.jpg?1573071455)

In addition to being a physically smaller and easier to lose chip, there are a few other difference as well. The chip itself exposes an interrupt pin for the magnetometer **(INTM)** (perhaps a feature of the new magnetometer sensor inside?) as well as chip select pins for both the accelerometer and magnetometer ( **CSA** and **CSM** respectively).

Another exciting difference between the two is the addition of two **[STEMMA QT](https://learn.adafruit.com/introducing-adafruit-stemma-qt)** connectors, one on each side of the board. This allows you to use the sensor without needing to solder as well as being able to chain it with other [STEMMA QT sensors](https://www.adafruit.com/?q=stemma%20qt).

Warning: 

# LSM303/LSM303DLHC

The older, or perhaps _more seasoned_ AdafruitLSM303 breakout uses the LSM303 **DLHC** and looks like this:

![](https://cdn-learn.adafruit.com/assets/assets/000/083/271/medium800/sensors_DLH_pinout_shot.png?1572454263)

Compared to the LSM303AGR, you can see that the sensor itself (the black rectangle in the center) is physically larger. Additionally the pins are in a different order and the LSM303DLH exposes a **DRDY** (data ready) pin.

# LSM303 Accelerometer + Compass Breakout

## Pinouts

![](https://cdn-learn.adafruit.com/assets/assets/000/083/722/medium800/sensors_top_crop.jpg?1573071442)

![](https://cdn-learn.adafruit.com/assets/assets/000/083/258/medium800/sensors_DLH_pinout_shot.png?1572393825)

# Power Pins

- **Vin** - this is the power pin. Since the sensor chip uses 3.3 VDC, we have included a voltage regulator on board that will take 3-5VDC and safely convert it down. To power the board, give it the same power as the logic level of your microcontroller - e.g. for a 5V microcontroller like Arduino, use 5V
- **3Vo** - this is the 3.3V output from the voltage regulator, you can grab up to 100mA from this if you like
- **GND** - common ground for power and logic

## I2C Logic Pins

- **SCL** - I2C clock pin, connect to your microcontroller's I2C clock line. This pin is level shifted so you can use 3-5V logic, and there's a **10K pullup** on this pin.
- **SDA** -I2C data pin, connect to your microcontroller's I2C data line. This pin is level shifted so you can use 3-5V logic, and there's a **10K pullup** on this pin.
- **[STEMMA QT](https://learn.adafruit.com/introducing-adafruit-stemma-qt)&nbsp;-** These connectors allow you to connectors to dev boards with&nbsp; **STEMMA QT** connectors or to other things with&nbsp;[various associated accessories](https://www.adafruit.com/?q=JST%20SH%204)

## Other Common Pins

- **IA1** - Tthe accelerometer's first interrupt pin. 3V logic only
- **IA2 -** The accelerometer's second interrupt pin. 3V logic only

## LSM303AGR Only

- **INTM** - The interrupt pin for the magnetometer. 3V logic only
- **CSA -** The accelerometer's CS pin. 3V logic only
- **CSM -** The magnetometer's CS pin. 3V logic only

Warning: 

## LSM303DLH Only

- **DRDY** - This is the data ready pin. 3V logic only

# LSM303 Accelerometer + Compass Breakout

## Assembly

![](https://cdn-learn.adafruit.com/assets/assets/000/004/708/medium800/adafruit_products_2013_03_01_IMG_1313-1024.jpg?1396815797)

## 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.![adafruit_products_2013_03_01_IMG_1314-1024.jpg](https://cdn-learn.adafruit.com/assets/assets/000/004/709/medium640/adafruit_products_2013_03_01_IMG_1314-1024.jpg?1396815808)

## 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.![adafruit_products_2013_03_01_IMG_1315-1024.jpg](https://cdn-learn.adafruit.com/assets/assets/000/004/710/medium640/adafruit_products_2013_03_01_IMG_1315-1024.jpg?1396815818)

## And Solder!
Solder each pin to assure a good electrical connection.  
  
If you are new to soldering, check out our [Guide to Excellent Soldering](http://learn.adafruit.com/adafruit-guide-excellent-soldering).![adafruit_products_2013_03_01_IMG_1316-1024.jpg](https://cdn-learn.adafruit.com/assets/assets/000/004/711/medium640/adafruit_products_2013_03_01_IMG_1316-1024.jpg?1396815828)

# LSM303 Accelerometer + Compass Breakout

## Arduino

# Arduino Wiring
- &nbsp;Connect&nbsp;**board VCC (red wire)** to&nbsp; **Arduino**  **5V** &nbsp;if you are running a **5V** board Arduino (Uno, etc.).&nbsp;If your board is **3V,** connect to that instead.
- Connect **board** **GND (black wire)&nbsp;**to&nbsp; **Arduino**  **GND**
- Connect **board** **SCL (yellow wire)&nbsp;**to&nbsp; **Arduino**  **SCL**
- Connect **board** **SDA (blue wire)&nbsp;**to&nbsp; **Arduino**  **SDA**

![robotics___cnc_ard_qt.png](https://cdn-learn.adafruit.com/assets/assets/000/083/238/medium640/robotics___cnc_ard_qt.png?1572384650)

![robotics___cnc_ard_bb.png](https://cdn-learn.adafruit.com/assets/assets/000/083/240/medium640/robotics___cnc_ard_bb.png?1572384694)

![robotics___cnc_arduino_DLH_bb.png](https://cdn-learn.adafruit.com/assets/assets/000/083/248/medium640/robotics___cnc_arduino_DLH_bb.png?1572385668)

## Install the Libraries

To get started with the LSM303, you'll need to install the accelerometer library and the magnetometer library for your board. Additionally you will need the [Adafruit\_Sensor](https://github.com/adafruit/Adafruit_Sensor) library that allows it to return data in a consistent way with other similar sensors, as well as the [Adafruit\_BusIO](https://github.com/adafruit/Adafruit_BusIO "https://github.com/adafruit/Adafruit\_BusIO") library. All of the libraries can be installed using the Library Manager in the Arduino IDE:

**Make sure you know [which version of the sensor](https://learn.adafruit.com/lsm303-accelerometer-slash-compass-breakout/which-lsm303-do-i-have) you have before continuing**

![](https://cdn-learn.adafruit.com/assets/assets/000/082/561/medium800/robotics___cnc_library_manager_menu.png?1571447211)

## Install the Accelerometer Library

Click the&nbsp; **Manage Libraries ...** &nbsp;menu item, search for&nbsp; **Adafruit LSM303 Accel** ,&nbsp;and select the&nbsp; **Adafruit\_LSM303\_Accel** &nbsp;library:

![](https://cdn-learn.adafruit.com/assets/assets/000/082/562/medium800/robotics___cnc_accel_install_libmgr.png?1571447260)

## Install the Magnetometer Library

Next you'll need to install the library for the magnetometer in the LSM303. Make sure to **download the correct driver for your breakout board**.

### LSM303AGR

Search the library manager for the **Adafruit\_LIS2MDL** library:

![](https://cdn-learn.adafruit.com/assets/assets/000/086/750/medium800/sensors_Arduino_LIS2MDL_libmgr.png?1578518144)

Info: 

### LSM303/LSM303DLHC

Search the library manager for the **Adafruit\_LSM303DLH\_Mag** library:

![](https://cdn-learn.adafruit.com/assets/assets/000/082/566/medium800/robotics___cnc_dlh_mag_install_libmgr.png?1571448315)

## Install the Helper Libraries
Follow the same process for the **Adafruit BusIO** library:

![](https://cdn-learn.adafruit.com/assets/assets/000/082/565/medium800/robotics___cnc_sensors_adafrtui_busio_arduino.png?1571447565)

Finally do the same for the&nbsp; **Adafruit Unified Sensor** library:

![](https://cdn-learn.adafruit.com/assets/assets/000/083/220/medium800/robotics___cnc_Unified_Sensor_LibMGR.png?1572381210)

# Accelerometer Demo

This first demo will show you how to get readings of what an accelerometer does best: measure acceleration!

Open up&nbsp; **File -\> Examples -\> Adafruit LSM303 Accel**** -\> accelsensor&nbsp;**and upload to your Arduino wired up to the sensor.

Upload the sketch to your board and open up the Serial Monitor ( **Tools -\> Serial Monitor** ) at **115200 baud**. You should see the the values for the current configuration settings printed on startup, followed by acceleration readings for the X, Y, and Z axes similar to this:

![](https://cdn-learn.adafruit.com/assets/assets/000/083/226/medium800/robotics___cnc_arduino_acceldemo_output.png?1572382926)

&nbsp;

The Adafruit\_LSM303\_Accel\_Unified sensor class in the Adafruit\_LSM303\_Accel library reports X, Y and Z axis accelerometer readings directly in [meters per second squared](http://en.wikipedia.org/wiki/Meter_per_second_squared "Link: http://en.wikipedia.org/wiki/Meter\_per\_second\_squared"). The [accelsensor example code](https://github.com/adafruit/Adafruit_LSM303_Accel/blob/master/examples/accelsensor/accelsensor.ino "Link: https://github.com/adafruit/Adafruit\_LSM303\_Accel/blob/master/examples/accelsensor/accelsensor.ino") 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](http://en.wikipedia.org/wiki/Inclinometer).

# Basic Magnetometer Readings

This first demo will show you how to get readings of what an accelerometer does best: measure acceleration!

### LSM303AGR

Open up&nbsp; **File -\> Examples -\> Adafruit LIS2MDL**** -\> magsensor** and upload to your Arduino wired up to the sensor.

### LSM303/LSM303DLH

Open up&nbsp; **File -\> Examples -\> Adafruit LSM303DLH Mag**** -\> magsensor** and upload to your Arduino wired up to the sensor.

Upload the sketch to your board and open up the Serial Monitor ( **Tools -\> Serial Monitor** ) at **115200 baud**. You should see the the values for the current configuration settings printed on startup, followed by magnetic field readings for the X, Y, and Z axes similar to this:

![](https://cdn-learn.adafruit.com/assets/assets/000/086/756/medium800/sensors_Arduino_LIS2MDL_magdemo_screeny.png?1578519661)

The sensor class in the magnetometer library reports X, Y and Z axis magnetometer readings directly in [micro-Teslas](http://en.wikipedia.org/wiki/Tesla_(unit)). The **magsensor** example code&nbsp;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](http://www.cplusplus.com/reference/cmath/atan2/) 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.

### LSM303AGR

Open up&nbsp; **File -\> Examples -\> Adafruit LIS2MDL**** -\> compass** and upload to your Arduino wired up to the sensor.

### LSM303/LSM303DLH

Open up&nbsp; **File -\> Examples -\> Adafruit LSM303DLH Mag**** -\> compass** and upload to your Arduino wired up to the sensor.

Upload the sketch to your board and open up the Serial Monitor ( **Tools -\> Serial Monitor** ) at **115200 baud**. You will see heading calculations printed out to the serial monitor. If you rotate the sensor as it runs you can see the heading change:

![](https://cdn-learn.adafruit.com/assets/assets/000/083/231/medium800/robotics___cnc_adruino_agr_compass_output.png?1572383869)

# Accelerometer Demo Code
https://github.com/adafruit/Adafruit_LSM303_Accel/blob/master/examples/accelsensor/accelsensor.ino

# LSM303AGR Magnetometer and Compass Code
https://github.com/adafruit/Adafruit_LIS2MDL/blob/master/examples/magsensor/magsensor.ino

https://github.com/adafruit/Adafruit_LIS2MDL/blob/master/examples/compass/compass.ino

# LSM303/LSM303DLH Magnetometer and Compass Code
https://github.com/adafruit/Adafruit_LSM303DLH_Mag/blob/master/examples/magsensor/magsensor.ino

https://github.com/adafruit/Adafruit_LSM303DLH_Mag/blob/master/examples/compass/compass.ino

Warning: 

The Adafruit\_LSM303DLHC Library for the [older LSM303DLH breakout](https://www.adafruit.com/product/1120) has been archived and replaced by [Adafruit\_LSM303\_Accel](https://github.com/adafruit/Adafruit_LSM303_Accel) and [Adafruit\_LSM303DLH\_Mag](https://github.com/adafruit/Adafruit_LSM303DLH_Mag) libraries which are used above. We recommend switching to the newer libraries as the old one will not be supported or have features added.  
  
If you still wish to use the old library, you can click the buttons below to go to the repository or download it as a ZIP

[Archived Adafruit_LSMDLHC Repository](https://github.com/adafruit/Adafruit_LSM303DLHC)
[Download Adafruit_LSM303DLHC](https://github.com/adafruit/Adafruit_LSM303DLHC/archive/master.zip)
# LSM303 Accelerometer + Compass Breakout

## Arduino Accel Docs

# LSM303 Accelerometer + Compass Breakout

## Arduino AGR Mag Docs

# LSM303 Accelerometer + Compass Breakout

## Arduino DLH Mag Docs

# LSM303 Accelerometer + Compass Breakout

## Python & CircuitPython

It's easy to use the LSM303 sensor with CircuitPython and the [Adafruit CircuitPython LSM303 Acceleromete](https://github.com/adafruit/Adafruit_CircuitPython_LSM303_Accel)[r](https://github.com/adafruit/Adafruit_CircuitPython_LSM303_Accel) and [Adafruit CircuitPython LIS2MDL](https://github.com/adafruit/Adafruit_CircuitPython_LIS2MDL)or [Adafruit CircuitPython LSM303DLH Magnetometer](https://github.com/adafruit/Adafruit_CircuitPython_LSM303DLH_Mag) libraries.&nbsp; These libraries allow you to easily write Python code that reads the accelerometer and magnetometer values 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](https://learn.adafruit.com/circuitpython-on-raspberrypi-linux).

**Make sure you know [which version of the sensor](https://learn.adafruit.com/lsm303-accelerometer-slash-compass-breakout/which-lsm303-do-i-have) you have before continuing**

# CircuitPython Microcontroller Wiring

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

- **Board 3V** &nbsp;to&nbsp;**sensor VIN (red wire)**
- **Board GND** &nbsp;to&nbsp;**sensor GND (black wire)**
- **Board SCL** &nbsp;to&nbsp;**sensor SCL (yellow wire)**
- **Board SDA** &nbsp;to&nbsp;**sensor SDA (blue wire)**
- &nbsp;

![robotics___cnc_py_feather_qt.png](https://cdn-learn.adafruit.com/assets/assets/000/083/208/medium640/robotics___cnc_py_feather_qt.png?1572379309)

![robotics___cnc_feather_bb.png](https://cdn-learn.adafruit.com/assets/assets/000/083/206/medium640/robotics___cnc_feather_bb.png?1572379239)

![robotics___cnc_feather_DLH_bb.png](https://cdn-learn.adafruit.com/assets/assets/000/083/249/medium640/robotics___cnc_feather_DLH_bb.png?1572385732)

# 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](https://learn.adafruit.com/circuitpython-on-raspberrypi-linux).&nbsp;

Here's the Raspberry Pi wired with I2C:

- **Pi 3V** &nbsp;to&nbsp;**sensor VIN (red wire)**
- **Pi GND** &nbsp;to&nbsp;**sensor GND (black wire)**
- **Pi SCL** &nbsp;to&nbsp;**sensor SCL (yellow wire)**
- **Pi SDA** &nbsp;to&nbsp;**sensor SDA (blue wire)**

![robotics___cnc_rpi_qt_wiring.png](https://cdn-learn.adafruit.com/assets/assets/000/083/210/medium640/robotics___cnc_rpi_qt_wiring.png?1572379412)

![robotics___cnc_lsm303dlh_rpi_bb.jpg](https://cdn-learn.adafruit.com/assets/assets/000/083/212/medium640/robotics___cnc_lsm303dlh_rpi_bb.jpg?1572379494)

![robotics___cnc_rpi_bb_wiring.png](https://cdn-learn.adafruit.com/assets/assets/000/083/213/medium640/robotics___cnc_rpi_bb_wiring.png?1572379647)

# CircuitPython Installation of LSM303 Library

Next you'll need to instal the [Adafruit CircuitPython LSM303](https://github.com/adafruit/Adafruit_CircuitPython_LSM303_Accel) accelerometer and [Adafruit CircuitPython LIS2MDL](https://github.com/adafruit/Adafruit_CircuitPython_LIS2MDL)&nbsp;or [Adafruit CircuitPython LSM303DLH](https://github.com/adafruit/Adafruit_CircuitPython_LSM303DLH_Mag) magnetometer (depending on [which LSM303 you have](https://learn.adafruit.com/lsm303-accelerometer-slash-compass-breakout/which-lsm303-do-i-have)) libraries on your CircuitPython board.&nbsp;&nbsp;

First make sure you are running the&nbsp;[latest version of Adafruit CircuitPython](../../../../welcome-to-circuitpython/installing-circuitpython)&nbsp;for your board.

Next you'll need to install the necessary libraries&nbsp;to use the hardware--carefully follow the steps to find and install these libraries from&nbsp;[Adafruit's CircuitPython library bundle](https://circuitpython.org/libraries).&nbsp; Our introduction guide has&nbsp;[a great page on how to install the library bundle](../../../../welcome-to-circuitpython/circuitpython-libraries)&nbsp;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\_lis2mdl.mpy or adafruit\_lsm303dlh\_mag.mpy**
- **adafruit\_lsm303\_accel.mpy**
- **adafruit\_bus\_device**
- **adafruit\_register**

Before continuing make sure your board's lib folder or root filesystem has the&nbsp; **adafruit\_lis2mdl.mpy or adafruit\_lsm303dlh\_mag.mpy,**  **adafruit\_lsm303\_accel.mpy, adafruit\_register,** and **&nbsp;adafruit\_bus\_device**** &nbsp; **files and folders** &nbsp;**copied over.

Next[&nbsp;connect to the board's serial REPL](https://learn.adafruit.com/welcome-to-circuitpython/the-repl) so you are at the CircuitPython&nbsp; **\>\>\>** &nbsp;prompt.

Info: 

## Python Installation of LSM303 Libraries

You'll need to install the **Adafruit\_Blinka** library that provides the CircuitPython support in Python. This may also require enabling I2C on your platform and verifying you are running Python 3.&nbsp;[Since each platform is a little different, and Linux changes often, please visit the CircuitPython on Linux guide to get your computer ready](https://learn.adafruit.com/circuitpython-on-raspberrypi-linux)!

Once that's done, from your command line run the following command:

- `sudo pip3 install adafruit-circuitpython-lsm303-accel`

Then install the magnetometer library for your version of the LSM303:

**LSM303AGR:**

- `sudo pip3 install adafruit-circuitpython-lis2mdl`

**LSM303DLH:**

- `sudo pip3 install adafruit-circuitpython-lsm303dlh-mag`

If your default Python is version 3 you may need to run 'pip' instead. Just make sure you aren't trying to use CircuitPython on Python 2.x, it isn't supported!

# CircuitPython & Python Usage
Warning: 

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:

### LSM303AGR
```python
import board
import adafruit_lsm303_accel
import adafruit_lis2mdl

i2c = board.I2C()
accel = adafruit_lsm303_accel.LSM303_Accel(i2c)
mag = adafruit_lis2mdl.LIS2MDL(i2c)
```

![](https://cdn-learn.adafruit.com/assets/assets/000/102/063/medium800/sensors_lsm303agr.png?1620526162)

### LSM303DLH
```python
import board
import adafruit_lsm303_accel
import adafruit_lsm303dlh_mag

i2c = board.I2C()
mag = adafruit_lsm303dlh_mag.LSM303DLH_Mag(i2c)
accel = adafruit_lsm303_accel.LSM303_Accel(i2c)
```

![](https://cdn-learn.adafruit.com/assets/assets/000/102/062/medium800/sensors_lsm303dlhc.png?1620525885)

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

**Accelerometer**

- **acceleration** - A 3-tuple of X, Y, Z acceleration values in meters per second per second (m/s^2).

**Magnetometer**

- **magnetic** - A 3-tuple of the X, Y, Z magnetometer readings in micro-Teslas.

```python
print("Acceleration (m/s^2): X=%0.3f Y=%0.3f Z=%0.3f"%accel.acceleration)
print("Magnetometer (micro-Teslas)): X=%0.3f Y=%0.3f Z=%0.3f"%mag.magnetic)
```

![](https://cdn-learn.adafruit.com/assets/assets/000/082/975/medium800/robotics___cnc_py_property_repl.png?1572046459)

# Tap Detection

The LSM303's accelerometer can also detect single or double taps!

&nbsp;

The **set\_tap** method can be used to set the number of taps (1 or 2) to detect, as well as setting a tap threshold. The lower the threshold, the more sensitive the accelerometer will be to detecting taps. You will likely have to play around with this number to find a value that suits your needs  
  
Here we're also going to use the **range** property to change the measurement range of the accelerometer to **+/-8G**

```python
accel.range = adafruit_lsm303_accel.Range.RANGE_8G
accel.set_tap(1, 30)
while True:
    if accel.tapped:
        print("Tapped!\n")
```

When you type code above into the REPL and give the sensor a nice solid tap, you should see something similar to the output below. If you don't see the **"Tapped!"** message, you may need to adjust the threshold.

![](https://cdn-learn.adafruit.com/assets/assets/000/083/266/medium800/sensors_tap_REPL_output.png?1572396153)

Warning: 

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.&nbsp; Save this as **code.py** on your board and open the REPL to see the output.

# Tap Detection Code
https://github.com/adafruit/Adafruit_CircuitPython_LSM303_Accel/blob/main/examples/lsm303_accel_tap_detection.py

# LSM303AGR Example Code
https://github.com/adafruit/Adafruit_Learning_System_Guides/blob/main/LSM303/lsm303agr_combined/code.py

# LSM303DLH Example Code
https://github.com/adafruit/Adafruit_Learning_System_Guides/blob/main/LSM303/lsm303dlh_combined/code.py

Warning: 

The Adafruit\_CircuitPython\_LSM303 Library for the [older LSM303DLH breakout](https://www.adafruit.com/product/1120) has been archived and replaced by [Adafruit\_CircuitPython\_LSM303\_Accel](https://github.com/adafruit/Adafruit_CircuitPython_LSM303_Accel) and [Adafruit\_CircuitPython\_LSM303DLH\_Mag](https://github.com/adafruit/Adafruit_CircuitPython_LSM303DLH_Mag) libraries which are used above. We recommend switching to the newer libraries as the old one will not be supported or have features added.  
  
If you still wish to use the old library, you can click the buttons below to go to the repository or download it as a ZIP

[Archived Adafruit_CircuitPython_LSM303 Repository](https://github.com/adafruit/Adafruit_CircuitPython_LSM303)
[Download Adafruit_CircuitPython_LSM303](https://github.com/adafruit/Adafruit_CircuitPython_LSM303/archive/master.zip)
# LSM303 Accelerometer + Compass Breakout

## Python Docs

# LSM303 Accelerometer + Compass Breakout

## Calibration

![](https://cdn-learn.adafruit.com/assets/assets/000/005/348/medium800/adafruit_products_cal_gui2.png?1396822962)

_(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](http://www.varesano.net/blog/fabio/freeimu-magnetometer-and-accelerometer-calibration-gui-alpha-version-out "Link: http://www.varesano.net/blog/fabio/freeimu-magnetometer-and-accelerometer-calibration-gui-alpha-version-out")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:&nbsp;&nbsp;[Two Point Calibration](https://learn.adafruit.com/calibrating-sensors/two-point-calibration)

### Calibration Sketch: LSM303AGR
https://github.com/adafruit/Adafruit_LSM303AGR_Mag/blob/master/examples/calibration/calibration.ino

### LSM303/LSM303DLH
https://github.com/adafruit/Adafruit_LSM303DLH_Mag/blob/master/examples/calibration/calibration.ino

# LSM303 Accelerometer + Compass Breakout

## Making Tracks!

Now let's use the LSM303 module to do some simple navigation!

Warning: 

![](https://cdn-learn.adafruit.com/assets/assets/000/005/513/medium800/adafruit_products_2013_03_08_IMG_1339-1024.jpg?1396824569)

> > _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](http://www.qcc.mass.edu/plafountaine/Zax.pdf). 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.

![](https://cdn-learn.adafruit.com/assets/assets/000/005/514/medium800/adafruit_products_2013_03_08_IMG_1325-1024.jpg?1396824579)

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

- [Adafruit LSM303 Breakout Board](https://www.adafruit.com/products/1120 "Link: https://www.adafruit.com/products/1120")  
- [Arduino Uno](https://www.adafruit.com/products/50 "Link: https://www.adafruit.com/products/50")  
- [Arduino Enclosure](https://www.adafruit.com/products/271 "Link: https://www.adafruit.com/products/271")  
- [Continuous Rotation Servo](https://www.adafruit.com/products/154 "Link: https://www.adafruit.com/products/154")  
- [Jumper Wires](https://www.adafruit.com/index.php?main_page=adasearch&q=premium+jumper)  
- Card-stock  
- Cardboard or Foam Core  

## 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. ```
#include &lt;Servo.h&gt; 
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.![adafruit_products_2013_03_08_IMG_1327-1024.jpg](https://cdn-learn.adafruit.com/assets/assets/000/005/520/medium640/adafruit_products_2013_03_08_IMG_1327-1024.jpg?1396824638)

![adafruit_products_2013_03_08_IMG_1328-1024.jpg](https://cdn-learn.adafruit.com/assets/assets/000/005/521/medium640/adafruit_products_2013_03_08_IMG_1328-1024.jpg?1396824649)

![adafruit_products_2013_03_08_IMG_1329-1024.jpg](https://cdn-learn.adafruit.com/assets/assets/000/005/522/medium640/adafruit_products_2013_03_08_IMG_1329-1024.jpg?1396824659)

![adafruit_products_2013_03_08_IMG_1330-1024.jpg](https://cdn-learn.adafruit.com/assets/assets/000/005/523/medium640/adafruit_products_2013_03_08_IMG_1330-1024.jpg?1396824669)

## 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.  
![adafruit_products_2013_03_08_IMG_1332-1024.jpg](https://cdn-learn.adafruit.com/assets/assets/000/005/524/medium640/adafruit_products_2013_03_08_IMG_1332-1024.jpg?1396824680)

![adafruit_products_2013_03_08_IMG_1333-1024.jpg](https://cdn-learn.adafruit.com/assets/assets/000/005/525/medium640/adafruit_products_2013_03_08_IMG_1333-1024.jpg?1396824688)

## 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.![adafruit_products_2013_03_08_IMG_1336-1024.jpg](https://cdn-learn.adafruit.com/assets/assets/000/005/526/medium640/adafruit_products_2013_03_08_IMG_1336-1024.jpg?1396824698)

![adafruit_products_2013_03_08_IMG_1348-1024.jpg](https://cdn-learn.adafruit.com/assets/assets/000/005/527/medium640/adafruit_products_2013_03_08_IMG_1348-1024.jpg?1396824709)

## Add Zaxen!
[Find an image of your favorite Zax](https://www.google.com/search?q=north+going+zax&hl=en&source=lnms&tbm=isch&sa=X&ei=PJM7UafvF83p0QH7qoGwBw&ved=0CAoQ_AUoAQ&biw=1920&bih=895). 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.![adafruit_products_2013_03_08_IMG_1338-1024.jpg](https://cdn-learn.adafruit.com/assets/assets/000/005/528/medium640/adafruit_products_2013_03_08_IMG_1338-1024.jpg?1396824719)

![adafruit_products_2013_03_08_IMG_1344-1024.jpg](https://cdn-learn.adafruit.com/assets/assets/000/005/529/medium640/adafruit_products_2013_03_08_IMG_1344-1024.jpg?1396824732)

![adafruit_products_2013_03_08_IMG_1325.jpg](https://cdn-learn.adafruit.com/assets/assets/000/005/533/medium640/adafruit_products_2013_03_08_IMG_1325.jpg?1396824800)

# 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! ```
// **********************************************
// Zax-O-Meter Sketch 
// for the Adafruit LSM303 Magnetometer Breakout
//
// Written by Bill Earl for Adafruit Industries
//
// **********************************************

#include &lt;Wire.h&gt;
#include &lt;Adafruit_Sensor.h&gt;
#include &lt;Adafruit_LSM303_U.h&gt;
#include &lt;Servo.h&gt;

/* 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(&amp;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 &lt; 0)
  {
    heading = 360 + heading;
  }
  
  // Calculate the error between tha measured heading and the target heading.
  float error = heading - targetHeading;
  if (error &gt; 180)
  {
    error = error - 360;  // for angles &gt; 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);
}
```

# LSM303 Accelerometer + Compass Breakout

## Downloads and Links

# Files

## LSM303AGR

- [LSM303AGR datasheet](https://www.mouser.com/datasheet/2/389/lsm303agr-954987.pdf)
- [PCB Files (Eagle Format)](https://github.com/adafruit/Adafruit-LSM303AGR-PCB "Link: https://github.com/adafruit/Adafruit-LSM303AGR-PCB")
- [Fritzing object in the Adafruit Fritzing library](https://github.com/adafruit/Fritzing-Library/raw/master/parts/Adafruit%20MPU6050.fzpz "https://github.com/adafruit/Fritzing-Library/raw/master/parts/Adafruit%20MPU6050.fzpz")

## LSM303DLHC

- [LSM303DLHC datasheet](https://cdn-shop.adafruit.com/datasheets/LSM303DLHC.PDF)
- [PCB Files (Eagle Format)](https://github.com/adafruit/Adafruit-LSM303-PCB "Link: https://github.com/adafruit/Adafruit-LSM303-PCB")
- [Fritzing object in the Adafruit Fritzing library](https://github.com/adafruit/Fritzing-Library)

# LSM0303AGR Schematic & Fab Print
![](https://cdn-learn.adafruit.com/assets/assets/000/083/160/medium800/robotics___cnc_agr_schmatic.png?1572307748)

![](https://cdn-learn.adafruit.com/assets/assets/000/083/161/medium800/robotics___cnc_agr_fab_print.png?1572307759)

# LSM303DLHC Schematic & Fabrication Print
![](https://cdn-learn.adafruit.com/assets/assets/000/036/164/medium800/adafruit_products_schem.png?1475618672)

![](https://cdn-learn.adafruit.com/assets/assets/000/036/166/medium800/adafruit_products_fabprin.png?1475618687)


## Primary Products

### Adafruit LSM303AGR Accelerometer Magnetometer - STEMMA QT Qwiic

[Adafruit LSM303AGR Accelerometer Magnetometer - STEMMA QT Qwiic](https://www.adafruit.com/product/4413)
Do you know which way the wind blows? You will now, with this triple-axis accelerometer/magnetometer compass module. Inside are two sensors, one is a classic 3-axis accelerometer, which can tell you which direction is down towards the Earth (by measuring gravity). The other is a magnetometer...

Out of Stock
[Buy Now](https://www.adafruit.com/product/4413)
[Related Guides to the Product](https://learn.adafruit.com/products/4413/guides)

## Featured Products

### Triple-axis Accelerometer+Magnetometer (Compass) Board - LSM303

[Triple-axis Accelerometer+Magnetometer (Compass) Board - LSM303](https://www.adafruit.com/product/1120)
Discontinued - **you can grab** [Adafruit LSM303AGR Accelerometer Magnetometer - STEMMA QT Qwiic](https://www.adafruit.com/product/4413) instead!

&nbsp;

He told you "Go West, young maker!" - but you don't know which way is West! Ah, if only you had this...

No Longer Stocked
[Buy Now](https://www.adafruit.com/product/1120)
[Related Guides to the Product](https://learn.adafruit.com/products/1120/guides)
### Adafruit METRO 328 Fully Assembled - Arduino IDE compatible

[Adafruit METRO 328 Fully Assembled - Arduino IDE compatible](https://www.adafruit.com/product/50)
We sure love the ATmega328 here at Adafruit, and we use them&nbsp;_a lot_&nbsp;for our own projects. The processor has plenty of GPIO, Analog inputs, hardware UART SPI and I2C, timers and PWM galore - just enough for most simple projects. When we need to go small, we use a <a...></a...>

Out of Stock
[Buy Now](https://www.adafruit.com/product/50)
[Related Guides to the Product](https://learn.adafruit.com/products/50/guides)
### White Enclosure for Arduino - Electronics enclosure

[White Enclosure for Arduino - Electronics enclosure](https://www.adafruit.com/product/271)
Discontinued - **you can check these [Arduino accessories](https://www.adafruit.com/category/346)&nbsp;instead!&nbsp;**

&nbsp;

We are very excited to have one of the first (and we think the best) Enclosure for Arduino & project box! Here are all the...

No Longer Stocked
[Buy Now](https://www.adafruit.com/product/271)
[Related Guides to the Product](https://learn.adafruit.com/products/271/guides)
### Continuous Rotation Servo

[Continuous Rotation Servo](https://www.adafruit.com/product/154)
This servo rotates fully forward or backward instead of moving to a position. You can use any servo code, hardware, or library to control these servos. Good for making simple moving robots. Comes with four different horns, as shown.

To control with an Arduino, we suggest connecting...

In Stock
[Buy Now](https://www.adafruit.com/product/154)
[Related Guides to the Product](https://learn.adafruit.com/products/154/guides)

## Related Guides

- [Adafruit Ultimate GPS](https://learn.adafruit.com/adafruit-ultimate-gps.md)
- [Arduino Lesson 6. Digital Inputs](https://learn.adafruit.com/adafruit-arduino-lesson-6-digital-inputs.md)
- [Cloud Thermometer](https://learn.adafruit.com/cloud-thermometer.md)
- [Adafruit SensorLab - Magnetometer Calibration](https://learn.adafruit.com/adafruit-sensorlab-magnetometer-calibration.md)
- [Arduin-o-Phone](https://learn.adafruit.com/arduin-o-phone-arduino-powered-diy-cellphone.md)
- [IR Sensor](https://learn.adafruit.com/ir-sensor.md)
- [20mm LED Pixels](https://learn.adafruit.com/20mm-led-pixels.md)
- [Wireless Gardening with Arduino + CC3000 WiFi Modules](https://learn.adafruit.com/wireless-gardening-arduino-cc3000-wifi-modules.md)
- [Arduino Lesson 16. Stepper Motors](https://learn.adafruit.com/adafruit-arduino-lesson-16-stepper-motors.md)
- [Digital Circuits 7: MCUs... how do they work?](https://learn.adafruit.com/mcus-how-do-they-work.md)
- [Adafruit Music Maker Shield](https://learn.adafruit.com/adafruit-music-maker-shield-vs1053-mp3-wav-wave-ogg-vorbis-player.md)
- [Trainable Robotic Arm](https://learn.adafruit.com/trainable-robotic-arm.md)
- [Tiny Arduino Music Visualizer](https://learn.adafruit.com/piccolo.md)
- [Automatic Monitor Color Temperature Adjustment](https://learn.adafruit.com/automatic-monitor-color-temperature-adjustment.md)
- [Bluetooth Controlled Motorized Camera Slider](https://learn.adafruit.com/bluetooth-motorized-camera-slider.md)
