XloBorg – compass & accelerometer for the Raspberry Pi

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

XloBorg Compass and Accelerometer

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)

# 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

This entry was posted in Technology. Bookmark the permalink. Follow any comments here with the RSS feed for this post. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>