I've have a 6DOF IMU from sparkfun (ITG3200/ADXL345) that is working great. In order to compensate for the drift in yaw, I purchased a magnetometer HMC5883L. I'm able to get data from the sensor, but the heading is completely wrong.

Do you have a compass ? A real one with a needle ? To compare with HMC5883L ?If the HMC5883L is near your computer or near wires or near a power supply, the magnetic direction would be influenced a lot.

You can use a long USB cable, and carefully rotate the sensor, and see what the output is.Perhaps you could even enlarge the distance to the other components.

The gyro will drift, but not that fast. Normally the magnetometer and the gyro combined in a filter will result in a stable heading.

Basically, you need to calibrate the compass. Have the raw X and Y data display on the serial terminal. rotate the compass to find the max X value, then rotate the compass 180 degrees and note this value. Also note the value of Y at this point.You need to offset the raw X and Y values, so that the magnitude of max X and Min X are similar. You also need to have the Y value near zero, as the X value is near its max or min value. Same goes for X , as Y is near it's min or max value X should be close to zero. Just keep adjusting the offset so you get as close as possible.

One problem is that the Y-value doesn't change much when i rotate the magnetometer about the Z-axis. The X-value changes from approx. -40 to 220, while the Y-value changes from -380 to -400. Is this normal?

With the help from the library, I finally got it working. Here is how I fixed it.

Based on the code provided by Pito, I made a 2D scatter plot. From the figure to the left, we see that the origin of the circle is not in (0,0). By subtracting the offset values, I was able to move the circle to (0,0). Now, by using atan2(y,x) the heading was calculated and it worked Figure: http://bildr.no/view/1613557Now I just have to figure out what I did wrong and they did right And then, tilt compensation XD

I played a lot with the chip in past and my lessons learned are as follows:1. do not put a strong magnet close to the chip..2. metallic objects (even small) close to the chip will destroy your scatter3. mag field in a living room is not defined..