LSM303DLHC magnetometer trouble with X register


I’m just testing a LSM303DLHC carrier board with a PIC18F4520 (in C language) at 100kHz clock, 30 Hz, ±8.1 gauss, in continuous mode.

I’m having some problems with the reading of the X register. I have noticed that it occurs when the value of the X register (raw data) comes greater or equal to 0. When that happens, the I2C communication with the sensor is lost. It’s just like the sensor doesn’t recognize the stop condition of the PIC, because I realized that the SSP interrupt flag on the PIC is not set after the stop condition (only when the X register is 0 or greater). I don’t have any problem with Y and Z registers.
After this, I can’t use the sensor unless I disconnect it and connect it again in a “correct” orientation (value of the X register less than 0).

I guess it’s not the program code, because I used it with other I2C devices and they work perfectly.

I attach some readings that I could get rotating the sensor through every axis. In readings where the X axis could take values greater or equal to 0, the reading gets frozen.

Thanks for your support.
Zaxis.log (3.61 KB)
Yaxis.log (4.24 KB)
Xaxis.log (4.46 KB)


I am sorry you are having trouble with the magnetometer.

Do you happen to have an Arduino around so you could try the library we wrote for the LSM303?

Do you have an oscilloscope so you can look at the I2C signals?

It is interesting that your problem only happens when the X value is greater than 0. The sign bit for the X register actually be the first bit that the PIC receives from the magnetometer when reading it. This makes me think that your code has some problem when the first received bit is 0.

You might have some misunderstanding about how the SSP module on the PIC works, especially if you are writing code that directly interfaces with it; it could be beneficial to try switching to software I2C just using digital outputs and inputs. At the very least, it will make it easier for us to understand what your code is doing.


Hi again!

I gave a try with an Arduino and the sensor worked. Therefore, I passed to check my code and finally found the error. The problem was in the mutiple bytes reception. When the last byte was received by the PIC, I was sending an ACK signal, but the correct signal has to be a NACK, and then, the Stop condition. This was causing that when the X register passed to 0 or greater, the SCL line was high and the SDA was low in the Stop condition, while the SDA line needs to be high. Because of this I couldn’t communicate with the device, unless disconnecting the LSM303 sensor.

I still wonder why the X register caused the problem, because I changed the first byte to be read one before, i.e. MR_REG_M, and the problem persists. But if I have news, will post them.

Anyway, I will continue with my project. =)

Thanks for your help.