Links
https://diydrones.com/m/blogpost?id=705844%3ABlogPost%3A1676387
If you bought the cheap magnetomter module like HMC5883L you can not use it without calibration. Measurement of magnetic field will be subjected to distortion. There are two categories of these distortions: the hard iron distortions and the soft iron distortions. The hard iron errors refer to the presence of magnetic fields around the sensor (magnets, power supply wires) and are related to measurement offset errors, while the soft iron errors refer to the presence of ferromagnetic materials around the sensor, which skew the density of the Earth’s magnetic field locally and are related to scaling offset errors.
A review of basic IMU sensors that work with Arduino, and how to interface Arduino with the best sensor available
https://maker.pro/arduino/tutorial/how-to-interface-arduino-and-the-mpu-6050-sensor
Playing with an Arduino and sensors
http://www.den-uijl.nl/electronics/gyro.html
6DOF Arduino: Compass & Accelerometer
Guide to gyro and accelerometer with Arduino including Kalman filtering
http://forum.arduino.cc/index.php/topic,58048.0.html
https://forum.arduino.cc/index.php?topic=329231.0
Outros
https://en.wikipedia.org/wiki/Gimbal_lock