hmc5883l magnetometer - not constant module ????

hello everyone, I'm Giuseppe, a not so happy owner of the hmc5883l 3-axis magnetometer . The sensor is supposed to be used ona quadcopter for the attitude determination, of course for yaw determination as you can imagine.

I'm experiencing some issues: as long as the mgm-sensor lays on a plane (no pitch, no roll) everything seems fine. When some roll and/or pitch rotations occur, everything went bad. I tried to implement some tilt compensation. But it didn't work... I'll ask you later about that

Digging deeper I found something weird was going on with the sensor: I asked for the serial print of the module of the three component and I was expecting for a constant value, no matter what the sensor orientation was. But it is not the case!!! :o

Any idaes/expanationa bout that?

here is the used library Library

and here is the code

#include "Wire.h"
#include "HMC5883L.h"

HMC5883L compass;

float mX,mY,mZ;

void setup(){

void loop(){
  MagnetometerRaw raw=compass.ReadRawAxis();
  float mod=sqrt(mX*mX+mY*mY+mZ*mZ);
  mX /= mod;
  mY /= mod;
  mZ /= mod;

Also the heading of the north with 2 any components atan2(mX,mZ), seems right ...

You need to calibrate the individual axis gains and offsets. This procedure works very well and is not difficult to implement.

Even if uncalibrated, wouldn’t the module of the 3-read-component be constant, would it?

No. If not calibrated, an acceleration of 1 g will give different values along each axis.

jremington: No. If not calibrated, an acceleration of 1 g will give different values along each axis.

What does acceleration have to do with a magnetometer?

I think you have a better understanding of IMU stuff than I do but I don't understand what you mean this time.

piepolitb: Even if uncalibrated, wouldn't the module of the 3-read-component be constant, would it?

Yes, I'd think so, but not absolutely constant.

I played with a HMC5883L a bunch myself and I found the output fluctuated but if the sensor were still and many readings were averaged, I'd get a very steady output from the averaged data.

I know the HMC5883L does internal averaging of up to 8 readings (IIRC) but this isn't enough for steady readings.

Of course averaging a bunch of readings isn't going to be practical on a quadcopter but it should work with a stationary sensor.

Sorry, I got confused, but the intent is the same. I should have typed:

No. If not calibrated, a constant magnetic field will produce different values when oriented along each axis.

To elaborate, individual gain and offset values must be obtained, such that the magnetometer reads the same when each axis is individually oriented parallel to the direction of the magnetic field.

The same holds true for accelerometers, but they are usually more accurate than magnetometers to begin with.

Thanks for clarifying jremington.