Wrong magnetic measurement

Hi,

I am trying to use the Nano 33 BLE to measure the movement of lifting objects. I want to be sure any rotation of the board does not interfere with the main movement along the z-axis so I am trying to combine the acceleration and magnetic movements to orient the board and subtract the gravity effect on the accelerometer.

The problem is that when I rotate the board the magnitude of the total magnetic field (sqrt(mx^2+my^2+mz^2)) changes a lot. I do not know if that's a problem of the board, the reading, or a very big problem of calibration.

I attach the code and an image of the total magnetic field as I rotate the board along the x-axis. The plot was done using a simple python code reading the serial output, but the effect is the same if I print the value of the magnetic field in the serial port.

Thanks!

code:

/*
Arduino LSM9DS1 - Simple Accelerometer
This example reads the acceleration values from the LSM9DS1
sensor and continuously prints them to the Serial Monitor
or Serial Plotter.
The circuit:

  • Arduino Nano 33 BLE Sense
    created 10 Jul 2019
    by Riccardo Rizzo
    This example code is in the public domain.
    */

#include <Arduino_LSM9DS1.h>
#include <Time.h>
/#include <TimeLib.h>/

void setup() {
Serial.begin(9600);
while (!Serial);
Serial.println("Started");
delay(15); // Wait >= 11 ms before first cmd

if (!IMU.begin()) {
Serial.println("Failed to initialize IMU!");
while (1);
}

Serial.print("Accelerometer sample rate = ");
Serial.print(IMU.accelerationSampleRate());
Serial.println(" Hz");
Serial.println();
Serial.println("Acceleration in G's");
Serial.println("X\tY\tZ");
}

void loop() {
float x, y, z;
float mx, my, mz;

unsigned long tmillis = millis(); // Get current time

if (IMU.accelerationAvailable() and IMU.magneticFieldAvailable()) {
IMU.readAcceleration(x, y, z);
IMU.readMagneticField(mx, my, mz);

Serial.print(x);
Serial.print(",");
Serial.print(y);
Serial.print(",");
Serial.print(z);
Serial.print(",");
Serial.print(tmillis);
Serial.print(",");
Serial.print(mx);
Serial.print(",");
Serial.print(my);
Serial.print(",");
Serial.println(mz);
delay(100);

}

}

Bmodule_vs_time.png

Can you please add code tags to your post, so the code gets displayed in a nice box? e.g.

Your example code

Have a look a the following post. This seems very similar.

https://forum.arduino.cc/index.php?topic=668641.0