title: Getting heading/direction from MPU-9250
body: <p>I'm trying to get the heading from the MPU-9250 sensor which contains a Gyroscope, Acceleratometer and Magnetometer using a Arduino.</p>
  
  <p>For my product I need to get the roll and the heading from the device. I already figured out how to fetch the roll. Using the Boulderflight MPU-9250 library I was able to determine the roll using:</p>
  
  <pre><code>roll = 180 * atan(accY/sqrt(accX*accX + accZ*accZ))/M_PI;
  </code></pre>
  
  <p>I found this calculation somewhere and it seems to work well, I have to admit that I don't actually know how it works. </p>
  
  <p>For the heading I found: </p>
  
  <pre><code>  if (magY &gt; 0) { heading = 90 - atan(magX/magY)*(180/M_PI); }
    else if (magY &lt; 0) { heading = 270 - atan(magX/magY)*(180/M_PI); }
    else if (magY == 0 &amp;&amp; magX &lt; 0) { heading = 180; }
    else if (magY == 0 &amp;&amp; magX &gt; 0) { heading = 0; }
  </code></pre>
  
  <p>This, at first, seemed to work but as soon as you would "roll" the device, keeping the heading the same, the values of the heading are all over the place. </p>
  
  <p>Does anyone have a good code snippet for determining the heading using either a Gyroscope, Accelerometer or Magnetometer (In C++, using an Arduino)?</p>