[Compass] Magnetometer Library (HMC5883)
This post includes a HMC5883 Magnetometer Library for Arduino. It contains a library that makes interfacing with a compass module (for arduino) in C++ very easy. There are other libraries for the HMC5843, but they are not compatible with the HMC5843. Other libraries i found for the HMC5883 of sample codes were either inefficient or plain incorrect. You can download the library if you scroll to the bottom.
There is a breakout for this module that Seeedstudios sell for about $25, which is a great deal and includes handling of some stuff we can now ignore; like the correct voltage (it accepts like 3~6V). Anyway. You can buy it here for just $25.
This is actually a 3 axis magnetometer for arduino, and does not contain tilt compensation. For big tilts you would need tilt compensation, but it is not strictly necessary.
How does a 3 axis magnetometer work?
It reads magnitudes in X Y and Z direction. Then using sine and cosine functions you can calculate the angle between them; thus obtaining the angle between the earths magnetic force and your little module.
This library is also not very efficient or versatile, but since it’s so simple, everyone understands it. It is as easy as:
delay(100); // There will be new values every 100ms
The code is based on the Seeeduino module, which provides more info about that here.