[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 […]

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.

Example

This library is also not very efficient or versatile, but since it’s so simple, everyone understands it. It is as easy as:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <wire.h>
#include <hmc.h>
int a;
 
void setup()
{
  Serial.begin(9600);
}
 
void loop()
{
  int x,y,z;
  delay(100); // There will be new values every 100ms
  HMC.getValues(&x,&y,&z);
  Serial.print("x:");
  Serial.print(x);
  Serial.print(" y:");
  Serial.print(y);
  Serial.print(" z:");
  Serial.println(z);
 
  HMC.getAngle(&a);
  Serial.println(a);
}

The code is based on the Seeeduino module, which provides more info about that here.

Download magnetometer code library

Download: HMC_library.zip