diff --git a/examples/lsm303dlh_mag_compass.py b/examples/lsm303dlh_mag_compass.py new file mode 100644 index 0000000..9927228 --- /dev/null +++ b/examples/lsm303dlh_mag_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_lsm303dlh_mag + +i2c = busio.I2C(board.SCL, board.SDA) +sensor = adafruit_lsm303dlh_mag.LSM303DLH_Mag(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)