Skip to content

adding compass example #5

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Feb 14, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions docs/examples.rst
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,12 @@ Ensure your device works with this simple test.
.. literalinclude:: ../examples/lis3mdl_simpletest.py
:caption: examples/lis3mdl_simpletest.py
:linenos:

Compass Example
---------------

Use the magnetometer to calculate compass headings.

.. literalinclude:: ../examples/lis3mdl_compass.py
:caption: examples/lis3mdl_compass.py
:linenos:
26 changes: 26 additions & 0 deletions examples/lis3mdl_compass.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
""" Display compass heading data five times per second """
import time
from math import atan2, degrees
import board
import busio
import adafruit_lis3mdl

i2c = busio.I2C(board.SCL, board.SDA)
sensor = adafruit_lis3mdl.LIS3MDL(i2c)


def vector_2_degrees(x, y):
angle = degrees(atan2(y, x))
if angle < 0:
angle += 360
return angle


def get_heading(_sensor):
magnet_x, magnet_y, _ = _sensor.magnetic
return vector_2_degrees(magnet_x, magnet_y)


while True:
print("heading: {:.2f} degrees".format(get_heading(sensor)))
time.sleep(0.2)