title: How to get a phone's azimuth with compass readings and gyroscope readings?
body: <p>I wish to get my phone's current orientation by the following method:</p>
  
  <ol>
  <li>Get the initial orientation (azimuth) first via the <code>getRotationMatrix()</code> and <code>getOrientation()</code>.</li>
  <li>Add the integration of gyroscope reading over time to it to get the current orientation.</li>
  </ol>
  
  <p><strong>Phone Orientation:</strong></p>
  
  <p>The phone's x-y plane is fixed parallel with the ground plane. i.e., is in a "texting-while-walking" orientation.</p>
  
  <p><strong>"<code>getOrientation()</code>" Returnings:</strong></p>
  
  <p>Android API allows me to easily get the orientation, i.e., azimuth, pitch, roll, from <code>getOrientation()</code>.</p>
  
  <p>Please <strong>note</strong> that this method <strong>always</strong> returns its value within the range: <strong><code>[0, -PI]</code></strong> and <strong><code>[o, PI]</code></strong>.</p>
  
  <p><strong>My Problem:</strong></p>
  
  <p>Since the integration of the gyroscope reading, denoted by <code>dR</code>, may be quite big, so when I do <code>CurrentOrientation += dR</code>, the <code>CurrentOrientation</code> may exceed the <strong><code>[0, -PI]</code></strong> and <strong><code>[o, PI]</code></strong> ranges.</p>
  
  <p><strong>What manipulations are needed so that I can ALWAYS get the current orientation within the  the <code>[0, -PI]</code> and <code>[o, PI]</code> ranges?</strong></p>
  
  <p>I have tried the following in Python, but I highly doubt its correctness.</p>
  
  <pre><code>rotation = scipy.integrate.trapz(gyroSeries, timeSeries) # integration
  if (headingDirection - rotation) &lt; -np.pi:
      headingDirection += 2 * np.pi
  elif (headingDirection - rotation) &gt; np.pi:
      headingDirection -= 2 * np.pi
  # Complementary Filter
  headingDirection = ALPHA * (headingDirection - rotation) + (1 - ALPHA) * np.mean(azimuth[np.array(stepNo.tolist()) == i])
  if headingDirection &lt; -np.pi:
      headingDirection += 2 * np.pi
  elif headingDirection &gt; np.pi:
      headingDirection -= 2 * np.pi
  </code></pre>
  
  <hr>
  
  <p><strong>Remarks</strong></p>
  
  <p>This is NOT that simple, because it involves the following trouble-makers:</p>
  
  <ol>
  <li>The orientation sensor reading goes from <code>0</code> to <code>-PI</code>, and then <strong>DIRECTLY JUMPS</strong> to <code>+PI</code> and gradually gets back to <code>0</code> via <code>+PI/2</code>.</li>
  <li>The integration of the gyrocope reading also leads to some trouble. Should I add <code>dR</code> to the orientation or subtract <code>dR</code>.</li>
  </ol>
  
  <p><strong>Do please refer to the Android Documentations first, before giving a confirmed answer.</strong></p>
  
  <p>Estimated answers will not help.</p>