How to get correct magnetometer data from MPU 9150

Hi,

I am currently working on a project where I use the MPU 9150 sensor.

I get accelerometer, gyro and magnetometer data as an output by calling the function void getMotion9(int16_t* ax, int16_t* ay, int16_t* az, int16_t* gx, int16_t* gy, int16_t* gz, int16_t* mx, int16_t* my, int16_t* mz) from this library

The output data for accelerometer and gyro seem to be comprehensible.
But the output data for the magnetometer don't make sense to me.
The following data are samples I took by moving the sensor.

The first column shows the degree from the starting position.

degree mx my mz
0 1714 2414 -754
90 2174 2794 -614
180 2564 2344 -824
270 2124 2044 -964

I then want to calculate the actual heading with the following formula:
heading = arctan2(mx,my)*180/pi

But this results in confusing headings that don't make sense.

Any idea what I am doing wrong or I can try to find the error?
If you need more information please don't hesitate to ask.

Thank you for your help!

All magnetometers must be calibrated, mounted where they will be used, in order to function correctly.

This tutorial describes the best approach, but there are simpler ones that may work in your situation.

Thank you jremington,

The tutorial you have linked seems to be very helpful for my problem!