# Calculate the degrees out of a magnetometer

Hello,

Im trying to get North, East, South, West out of the Magnetometer.
I’m using the Arduino ZERO + NB-IoT shield, with Sodaq_LSM303AGR library.
The code i use is:

Init Magnetometer:

void initAccMagSensor(int8_t timer, int16_t timeout) {
accMagSensor = new Sodaq_LSM303AGR();
accMagSensor->rebootAccelerometer();
delay(timeout);
accMagSensor->rebootMagnetometer();
delay(timeout);
accMagSensor->enableAccelerometer(accMagSensor->HighResMode,accMagSensor-HrNormalLowPower100Hz, accMagSensor->XYZ, accMagSensor->Scale2g);
accMagSensor->enableMagnetometer(accMagSensor->MagHighResMode,accMagSensor-Hz100,accMagSensor->Continiuous);
delay(timer);
}

For getting the Axes:

double getMXAs() {
return accMagSensor->getMagX();
}

double getMYAs() {
return accMagSensor->getMagY();
}

double getMZAs() {
return accMagSensor->getMagZ();
}

I’ll get the average of 10 samples to get stabe numbers with the next code:

double middleAxes(String type, int8_t factor) {
double middle = 0;
for (int i = 0; i < (factor-1); i++) {
if (type.equals(“axas”)) {
middle += getAXAs();
} else if (type.equals(“ayas”)) {
middle += getAYAs();
} else if (type.equals(“azas”)) {
middle += getAZAs();
} else if (type.equals(“mxas”)) {
middle += getMXAs();
} else if (type.equals(“myas”)) {
middle += getMYAs();
} else if (type.equals(“mzas”)) {
middle += getMZAs();
}
}
return middle / factor;
}

Next up, I’m calculating the degrees with this code (this is done with the blog found on: https://blog.digilentinc.com/how-to-convert-magnetometer-data-into-compass-heading/):

int32_t getDegrees(){
double xGaussData = middleAxes(“mxas”, middleFactor);
double yGaussData = middleAxes(“myas”, middleFactor);
xGaussData *= 0.48828125;
yGaussData = 0.48828125;
if (xGaussData == 0 && yGaussData < 0){
} else if (yGaussData >= 0){
} else if (xGaussData != 0) {
(180/PI);

}
}
}

return 0;
}

To get a string out of the degrees i use the next code:

String Course;
Course = “North”;
Course = “North-West”;
Course = “West”;
Course = “South-West”;
Course = “South”;
Course = “South-East”;
Course = “East”;
Course = “North-East”;
}
DEBUG_STREAM.println("\t Course: " + Course);
}

The result i get is not what you should expect,
By what should be 0 degrees:

getMagX: -229.50 getMagY: -6.00 getMagZ: -720.00 heading: 1.61
Course: North

By what should be 90 degrees:

getMagX: 48.00 getMagY: -180.00 getMagZ: -711.00 heading: 286.24
Course: West

By what should be 180 degrees:

getMagX: -121.50 getMagY: -447.00 getMagZ: -738.00 heading: 75.56
Course: East

By what should be 270 degrees:

getMagX: -412.50 getMagY: -270.00 getMagZ: -733.50 heading: 33.12
Course: North-East

Like you see above this is nothing like it should be,
What im doing wrong?