Please see the project page on my blog to download the sources, and for a more complete discussion of the project particulars.

I've been working on this thing (more off than on!) for a long time. There's a series of eight articles I wrote about all the steps (and mis-steps) and building blocks that went into it.

One article in particular I want to call attention to is the one that explains the math behind the transformations I use to turn the 3-axis magnetometer reading into a compass heading.