/ examples / lsm303dlh_mag_compass.py
lsm303dlh_mag_compass.py
 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_lsm303dlh_mag
 7  
 8  i2c = busio.I2C(board.SCL, board.SDA)
 9  sensor = adafruit_lsm303dlh_mag.LSM303DLH_Mag(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)