Thanks for the replies, here's the code - I tried multiple libraries / examples , this is the Spakrfun library taken from here
I only changed the format the values are printed so it would fit to the serial plotter.
if (imu.begin() == false) // with no arguments, this uses default addresses (AG:0x6B, M:0x1E) and i2c port (Wire).
Serial.println("Failed to communicate with LSM9DS1.");
// tried with both of these and without, still values doesn't makes sense
// Calculate pitch, roll, and heading.
// Pitch/roll calculations take from this app note:
// Heading calculations taken from this app note:
void printAttitude(float ax, float ay, float az, float mx, float my, float mz)
float roll = atan2(ay, az);
float pitch = atan2(-ax, sqrt(ay * ay + az * az));
if (my == 0)
heading = (mx < 0) ? PI : 0;
heading = atan2(mx, my);
heading -= DECLINATION * PI / 180;
if (heading > PI) heading -= (2 * PI);
else if (heading < -PI) heading += (2 * PI);
// Convert everything from radians to degrees:
heading *= 180.0 / PI;
pitch *= 180.0 / PI;
roll *= 180.0 / PI;
// Update the sensor values whenever new data is available
if ( imu.gyroAvailable() )
if ( imu.accelAvailable() )
if ( imu.magAvailable() )
if ((lastPrint + PRINT_SPEED) < millis())
// Print the heading and orientation for fun!
// Call print attitude. The LSM9DS1's mag x and y
// axes are opposite to the accelerometer, so my, mx are
// substituted for each other.
printAttitude(imu.ax, imu.ay, imu.az,
-imu.my, -imu.mx, imu.mz);
lastPrint = millis(); // Update lastPrint time
At first I got Pitch, Roll that looked ok but now the values are not consistent - The pitch looks consistent but the roll changes with pitch as I'm tilting the device up and I got some roll peaks here and there.
The Heading is moving with the pitch and roll , if the the device is rotating on a flat surface the heading looks ok (except of some peaks sometimes- screenshot attached) but when I'm tilting the device up or down the heading moves.
I attached some screenshot from the serial plotter, hope it's enough info to understand the issue.
Serial monitor values while the devices sits on a flat surface (table):