Electronic – Unexpected YAW angle from magnetometer

calibrationmagnetometer

I have some doubts about a magnetometer application.

I am trying to get YAW angle value from magnetometer data and so I am doing the following:

mag_x_data 

mag_y_data

    yaw=arctang(mag_y_data / mag_x_data);
    yaw=yaw * (Rad_to_degree)

After successfully calibrating it, if I work in the xy plane without moving it, I get successful results.

The problem arises when, for example, I move the magenetometer in the x axis (rotating the magnetometer in x axis – ROLL angle)
and leaving YAW still, the result of the YAW changes. I understand that this should not happen.

Am I getting it wrong?

What should I do to obtain the YAW values, ​​independent of the position of the X and Y axis, with the magnetometer data?

When I refer to YAW I am talking about rotations in the z axis. Assuming the xy plane corresponds to the surface plane, and the z axis is colinear to Earth's gravity.

Best Answer

There may also be other things at play, but this could well be what the problem is: the magnetic field is only horizontal at the equator; everywhere else there is a vertical component in the magnetic vector.

Rolling the magnometer will show a part of that vertical component in your x and y values, and give you a wrong bearing.

What you would need to counter that is commonly called tilt compensation, using accelerometers or other sensors. I can't reproduce the math off the top of my head, but it is easily googled; http://www.brokking.net/YMFC-32/YMFC-32_document_1.pdf is a good read.