The code presented on this page can be downloaded or found in the Arduino examples menu under Examples → SpinWearables → Compass → Calibrate.

A Calibration Procedure for the Magnetic Sensor


#include "SpinWearables.h"
using namespace SpinWearables;

void setup() {
  // Ensure all of the SpinWheel hardware is on.
  SpinWheel.begin();
  // Set up communication with the host computer.
  Serial.begin(9600);
}

float minx, miny, minz, maxx, maxy, maxz;

void loop() {
  // Read all sensor data.
  SpinWheel.readIMU();

  // Measure the magnetic field along the three axes of the sensor.
  float x = SpinWheel.mx;
  float y = SpinWheel.my;
  float z = SpinWheel.mz;

  if (x > maxx) maxx=x;
  if (y > maxy) maxy=y;
  if (z > maxz) maxz=z;
  if (x < minx) minx=x;
  if (y < miny) miny=y;
  if (z < minz) minz=z;

  float truex = x - (maxx+minx)/2;
  float truey = y - (maxy+miny)/2;
  float truez = z - (maxz+minz)/2;

  // Report it back to the host computer.
  Serial.print(x);
  Serial.print("\t"); // Print a tab separator.
  Serial.print(y);
  Serial.print("\t"); // Print a tab separator.
  Serial.print(z);
  Serial.print("\n"); // Print a new line.
}