## XloBorg – compass & accelerometer for the Raspberry Pi

### Posted by Mike Redrobe | Posted in Technology | Posted on 20-06-2013

#### 0

This week, PiBorg released XLoBorg – a 3 Axis Accelerometer and 3 Axis Magnetometer add-on for the Raspberry Pi

Since its so new the current software only gives the raw magnetometer x y z values:

`mX = +00371, mY = -00053, mZ = +02539`

Magnetic flux strength values aren’t much use to us mere humans,
what we really want is a nice easy 0-360 degree heading value.

Maths to the rescue !

We can find the angle from those “lengths” with arc tan Y/X

`heading = math.atan2 (mY,mX)`
(For simplicity I’m assuming the Pi is level… a more complicated method would include accelerometer data)

Here’s my full python code to read the sensor, and convert to degrees:

`#!/usr/bin/env python`

``` # Load the XLoBorg library import XLoBorg # Load maths library import math # Tell the library to disable diagnostic printouts XLoBorg.printFunction = XLoBorg.NoPrint # Start the XLoBorg module (sets up devices) XLoBorg.Init() # Read and display the raw magnetometer readings mx,my,mz = XLoBorg.ReadCompassRaw() print 'mX = %+06d, mY = %+06d, mZ = %+06d' % XLoBorg.ReadCompassRaw() # get the heading in radians heading = math.atan2 (my,mx) # Correct negative values ```

```if (heading < 0): heading = heading + (2 * math.pi) # convert to degrees heading = heading * 180/math.pi; print 'Heading: ', heading ```

Much better:

```mX = +00371, mY = -00053, mZ = +02539 Heading: 351 degrees```