• # Using a 3-Axis Magnetometer as a compass.

## An example:

### First Zero the magnetometer

For each axis X, Y and Z point the axis North and take a reading R1, then turn the magnetometer 180 degrees and take reading R2. Take the average of the two readings as the offset for that axis.
Your code will then take a reading and subtract the offset for each axis. X= Xraw- Xoffset, Y= Yraw- Yoffset, Z= Zraw- Zoffset.
Use the resulting Z, Y and Z values in all calculations that follow. If you repeat the North and then rotate proceedure then
Xn =-Xs, Yn=-Yz, and Zn=-Zs, where the subscripts s and n stanf for North and South.

### Example

• Assign the Z axis to the Yaw axis.
• Assign the X axis to the roll (heading) axis.
• Assign the Y axis to the pitch axis.
• With the X and Y axis level and the Z axis pointing in the position for use ( Think the model airplane is not inverted):
• Point the roll (X) axis North and note the sign of the X axis reading. If it is negative, you need to multiply X by -1 in the assignment statement of the code
• Point the roll (X) axis East and note the sign of the Y axis. The reading should be negative, if not you need to multiply Y by -1 in the assignment statement of the code
• The yaw axis should be positive in the Northern hemisphere and negative in the Southern menisphere. If not negate it.

``````var X=1,Y=-1,Z=1;
var X1,Y1,Z1;
var Xoffset=0,Yoffset=0,Zoffset=0;
//Read the magnetometer X,Y, and Z

//Subtract the offsets
X1=X-Xoffset; Y1=Y-Yoffset; Z1=Z-Zoffset;
//Assign the XYZ to roll pitch and yaw axis
var Sroll=1; var Spitch=-1; var Syaw=1;
roll=Sroll*X1; pitch=Spitch*Y1; yaw=Syaw*Z1;
dip=180/Math.PI*Math.atan(Math.sqrt(roll­*roll+pitch*pitch),yaw);
console.log("Dip= ",dip);