<< Summary

Use the Adafruit LSM303 with a Raspberry PI, in Java Raspberry PI
Accelerometer and Magnetometer

The board we are talking about here is the Adafruit Triple-axis Accelerometer+Magnetometer (Compass) Board - LSM303.

It has an I2C (pronounce I "square" C) interface, that needs to be enabled on the Raspberry PI.
I2C stands for Inter-Integrated-Circuit.
Arduino & Adafruit provide python libraries that go along with their components. The code we present here is in big part an adaptation of this code.

Enable I2C on the Raspberry PI

This step is already described in another document.
Once this is done, and the board wired, i2cdetect should produce an output like this:

  Prompt> sudo i2cdetect -y 1
       0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f
  00:          -- -- -- -- -- -- -- -- -- -- -- -- --
  10: -- -- -- -- -- -- -- -- -- 19 -- -- -- -- 1e --
  20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
  30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
  40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
  50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
  60: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
  70: -- -- -- -- -- -- -- --
      
Notice the rendered addresses, 0x19, and 0x1e.
In the code, those addresses are used by

  public final static int LSM303_ADDRESS_ACCEL = (0x32 >> 1); // 0011001x, 0x19
  public final static int LSM303_ADDRESS_MAG   = (0x3C >> 1); // 0011110x, 0x1E
      

Wiring

LSM303Raspberry PI
Vin2. 5.0 VDC Power
GND6. 0V (Ground)
SDA3. SDA0 (I2C)
SCL5. SCL0 (I2C)
Raspberry PI P1 Connector map Click to enlarge

Running

The class to run is adafruiti2c.AdafruitLSM303. Run it from a script like this:

 #!/bin/bash
 PI4J_HOME=/home/pi/pi4j/pi4j-distribution/target/distro-contents
 CP=./classes
 CP=$CP:$PI4J_HOME/lib/pi4j-core.jar
 sudo java -cp $CP adafruiti2c.AdafruitLSM303
      
The output would look like this:

 Starting sensors reading:
 Connected to bus. OK.
 Connected to devices. OK.
 Accelerometer OK.
 Magnetometer OK.
 accel (X: -4, Y: -16, Z: -8) mag (X: -159, Y: -110, Z: -242, heading: 215)
 accel (X: 0, Y: 0, Z: 0) mag (X: -159, Y: -109, Z: -243, heading: 214)
 accel (X: -76, Y: -4, Z: 1040) mag (X: -158, Y: -109, Z: -243, heading: 215)
 accel (X: -76, Y: -4, Z: 1040) mag (X: -158, Y: -109, Z: -243, heading: 215)
 accel (X: -8, Y: -16, Z: -8) mag (X: -156, Y: -106, Z: -241, heading: 214)
 accel (X: -8, Y: -16, Z: -8) mag (X: -156, Y: -106, Z: -241, heading: 214)
 accel (X: -76, Y: -12, Z: 1028) mag (X: -161, Y: -109, Z: -244, heading: 214)
 accel (X: -76, Y: -12, Z: 1028) mag (X: -161, Y: -109, Z: -244, heading: 214)
 accel (X: -76, Y: -4, Z: -8) mag (X: -159, Y: -109, Z: -245, heading: 214)
 accel (X: -76, Y: -4, Z: -8) mag (X: -159, Y: -109, Z: -245, heading: 214)
 ....
      

And what next?

Driving the Raspberry PI, on its own cart...


Oliv did it