Skip to content

Instantly share code, notes, and snippets.

@berikv
Forked from timtrueman/heading.py
Last active May 6, 2018 21:24
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save berikv/5568101 to your computer and use it in GitHub Desktop.
Save berikv/5568101 to your computer and use it in GitHub Desktop.
- Fix wrap to allow for bigger angles - Replace the hardcoded declination correction with an argument
def wrap(angle):
while angle > 2 * pi:
angle -= 2 * pi
while angle < 0:
angle += 2 * pi
return angle
def magnetometer_readings_to_tilt_compensated_heading(bx, by, bz, phi, theta, declinationRadians=0):
""" Takes in raw magnetometer values, pitch and roll and turns it into a tilt-compensated heading value ranging from -pi to pi (everything in this function should be in radians).
The correct value for declinationRadians can be found online: http://magnetic-declination.com/countries.php note that this value is in radians, not in degrees.
"""
Xh = bx * cos(theta) + by * sin(phi) * sin(theta) + bz * cos(phi) * sin(theta)
Yh = by * cos(phi) - bz * sin(phi)
return wrap((atan2(-Yh, Xh) + declinationRadians))
@ViennaMike
Copy link

The site listed in the comments for finding declination in radians was giving me problems as of May 2018 (it seemed to only show the 1st page of results for each letter of the alphabet). An alternative is https://www.ngdc.noaa.gov/geomag-web/#declination. This will give the declination in degrees and minutes, but then a site like this one (https://www.metric-conversions.org/angle/degrees-to-radians.htm) will do the conversion easily.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment