LSM303DLM magnetometer

Hi all,

I’ve looked through the forum here, but I’m not finding anything helpful to my problem.

I’ve got the LSM303 hooked up to my Arduino Mega, and they talk just fine. I was getting strange readings for the X axis when I tried to calibrate it (using the ‘Calibrate’ code). On further inspection, I found that I’m getting no reading for the X-axis of the magnetometer (for example):

A X: -17 Y: 32 Z: 1069 M X: -4096 Y: 157 Z: 501
A X: -15 Y: 38 Z: 1055 M X: -4096 Y: 159 Z: 503
A X: -6 Y: 22 Z: 1049 M X: -4096 Y: 158 Z: 500
A X: -16 Y: 32 Z: 1080 M X: -4096 Y: 152 Z: 500
A X: -27 Y: -12 Z: 1060 M X: -4096 Y: 154 Z: 500

I’ve tried some older code from GitHub (though it might have been a recent update) and I’ve tried slowing down the I2C bus (to 10kHz). I also added a cap on the boards input in case it was power related, and shortened all the wires in case it was a physical issue.

Anyways, I’m stumped. It’s the sample code, so I doubt that’s the problem. Maybe it’s timing related (as the X-axis is the first register requested by the library code). Maybe the magnetometer gets the request for data, and responds before it has a reading for the X-axis??

Anyone encountered this before? Ideas of what I should be looking at?

Are you sure that you are using the correct code for the LSM303DLM? Different versions of this chip differ in how the axes are addressed. From the product description

That was my first thought too, but I’ve checked my order and the bag it came in - all say LSM303DLM. And the comments in the code are definitely for the LSM303DLM.

OK, pretty sure I’ve got it.

I was wondering if the consistently wrong value was a sign of an overflow of some sort, so I adjusted the magnetometer sensitivity/range from the default of 1.3, to the max of 8.1, and it worked. With a bit of experimentation, I found the range of 4.0 (magGain_40) works consistently (2.5 works intermittently).

So to summarise, adding the line


to my setup routine fixed it. It’s now calibrated, and it’s giving a heading about 2 degrees ahead of the compass on my phone (I’ll have to dig out a real compass tomorrow).

Anyways, hope this helps someone in the future.

Thanks DarkYendor for finding this solution.

I had the same issue with the LSM303 on the ZumoShield. In my case, it was the z-axis magnetometer measurement that would peg at -4096 when I tilted the shield toward vertical. I was able to use


to change the magnetometer gain and eliminate this issue.