Skip to content

Commit 594c76d

Browse files
authored
Merge pull request #5 from FoamyGuy/master
adding compass example
2 parents ac70d83 + e8ae726 commit 594c76d

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

docs/examples.rst

+9
Original file line numberDiff line numberDiff line change
@@ -6,3 +6,12 @@ Ensure your device works with this simple test.
66
.. literalinclude:: ../examples/lis3mdl_simpletest.py
77
:caption: examples/lis3mdl_simpletest.py
88
:linenos:
9+
10+
Compass Example
11+
---------------
12+
13+
Use the magnetometer to calculate compass headings.
14+
15+
.. literalinclude:: ../examples/lis3mdl_compass.py
16+
:caption: examples/lis3mdl_compass.py
17+
:linenos:

examples/lis3mdl_compass.py

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
""" Display compass heading data five times per second """
2+
import time
3+
from math import atan2, degrees
4+
import board
5+
import busio
6+
import adafruit_lis3mdl
7+
8+
i2c = busio.I2C(board.SCL, board.SDA)
9+
sensor = adafruit_lis3mdl.LIS3MDL(i2c)
10+
11+
12+
def vector_2_degrees(x, y):
13+
angle = degrees(atan2(y, x))
14+
if angle < 0:
15+
angle += 360
16+
return angle
17+
18+
19+
def get_heading(_sensor):
20+
magnet_x, magnet_y, _ = _sensor.magnetic
21+
return vector_2_degrees(magnet_x, magnet_y)
22+
23+
24+
while True:
25+
print("heading: {:.2f} degrees".format(get_heading(sensor)))
26+
time.sleep(0.2)

0 commit comments

Comments
 (0)