Simple tests
Ensure your device works with these simple tests.
examples/lsm303dlh_mag_simpletest.py
1# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
2# SPDX-License-Identifier: MIT
3
4"""Display magnetometer data once per second"""
5
6import time
7
8import board
9
10import adafruit_lsm303dlh_mag
11
12i2c = board.I2C() # uses board.SCL and board.SDA
13# i2c = board.STEMMA_I2C() # For using the built-in STEMMA QT connector on a microcontroller
14sensor = adafruit_lsm303dlh_mag.LSM303DLH_Mag(i2c)
15
16while True:
17 mag_x, mag_y, mag_z = sensor.magnetic
18
19 print(f"Magnetometer (gauss): ({mag_x:10.3f}, {mag_y:10.3f}, {mag_z:10.3f})")
20 print("")
21 time.sleep(1.0)
Fast Data Reading Example
Fast readings example
examples/lsm303dlh_mag_fast.py
1# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
2# SPDX-License-Identifier: MIT
3
4"""Read data from the magnetometer and print it out, ASAP!"""
5
6import board
7
8import adafruit_lsm303dlh_mag
9
10i2c = board.I2C() # uses board.SCL and board.SDA
11# i2c = board.STEMMA_I2C() # For using the built-in STEMMA QT connector on a microcontroller
12sensor = adafruit_lsm303dlh_mag.LSM303DLH_Mag(i2c)
13
14while True:
15 mag_x, mag_y, mag_z = sensor.magnetic
16 print(f"{mag_x:10.3f} {mag_y:10.3f} {mag_z:10.3f}")
Compass Example
Magnetic compass example
examples/lsm303dlh_mag_compass.py
1# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
2# SPDX-License-Identifier: MIT
3
4"""Display compass heading data five times per second"""
5
6import time
7from math import atan2, degrees
8
9import board
10
11import adafruit_lsm303dlh_mag
12
13i2c = board.I2C() # uses board.SCL and board.SDA
14# i2c = board.STEMMA_I2C() # For using the built-in STEMMA QT connector on a microcontroller
15sensor = adafruit_lsm303dlh_mag.LSM303DLH_Mag(i2c)
16
17
18def vector_2_degrees(x, y):
19 angle = degrees(atan2(y, x))
20 if angle < 0:
21 angle += 360
22 return angle
23
24
25def get_heading(_sensor):
26 magnet_x, magnet_y, _ = _sensor.magnetic
27 return vector_2_degrees(magnet_x, magnet_y)
28
29
30while True:
31 print(f"heading: {get_heading(sensor):.2f} degrees")
32 time.sleep(0.2)