CodeGirl42 has written a very comprehensive tutorial that teaches you all about GPS and taking magnetic North bearings using a magnetometer. There’s a lot of maths involved, but she takes you through it and then creates a C++ script to carry out the task. Take a look here.