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
7import board
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
17 print(
18 "Magnetometer (gauss): ({0:10.3f}, {1:10.3f}, {2:10.3f})".format(
19 mag_x, mag_y, mag_z
20 )
21 )
22 print("")
23 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
7import adafruit_lsm303dlh_mag
8
9i2c = board.I2C() # uses board.SCL and board.SDA
10# i2c = board.STEMMA_I2C() # For using the built-in STEMMA QT connector on a microcontroller
11sensor = adafruit_lsm303dlh_mag.LSM303DLH_Mag(i2c)
12
13while True:
14 mag_x, mag_y, mag_z = sensor.magnetic
15 print("{0:10.3f} {1:10.3f} {2:10.3f}".format(mag_x, mag_y, mag_z))
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 """
5import time
6from math import atan2, degrees
7import board
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
14
15def vector_2_degrees(x, y):
16 angle = degrees(atan2(y, x))
17 if angle < 0:
18 angle += 360
19 return angle
20
21
22def get_heading(_sensor):
23 magnet_x, magnet_y, _ = _sensor.magnetic
24 return vector_2_degrees(magnet_x, magnet_y)
25
26
27while True:
28 print("heading: {:.2f} degrees".format(get_heading(sensor)))
29 time.sleep(0.2)