diff --git a/docs/examples.rst b/docs/examples.rst index 0f28ac2..2765e25 100644 --- a/docs/examples.rst +++ b/docs/examples.rst @@ -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: \ No newline at end of file diff --git a/examples/lis3mdl_compass.py b/examples/lis3mdl_compass.py new file mode 100644 index 0000000..84d6ac8 --- /dev/null +++ b/examples/lis3mdl_compass.py @@ -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)