HMC5883L compass - weird behaviour.

I'd be interested in other peoples experiences with this sensor.

I'm using a MEGA with the Adafruit code for magcompass. It sits atop a large Meccano robot - so lots of metal and motor magnetic fields! A standard non electronic compass works OK in this position. I only need heading data - no inclination. Now, with the compass used to measure heading using the x and y axis,results are all over the place. However, reorientating the compass to use z and x axis, results are pretty good. Anyone else experienced this and why?

Magnetometer compasses MUST be calibrated, at the very least to remove gain and offset errors. Here are two techniques, in order of increasing accuracy and sophistication:

Edit: for best results the magnetometer should be calibrated in the robot, to correct for local distortions of the magnetic field. In some situations corrections may not be possible, in which case you may have to install it differently.