Simple tests¶
Ensure your device works with these simple tests.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | # SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
# SPDX-License-Identifier: MIT
""" Display magnetometer data once per second """
import time
import board
import adafruit_lsm303dlh_mag
i2c = board.I2C() # uses board.SCL and board.SDA
sensor = adafruit_lsm303dlh_mag.LSM303DLH_Mag(i2c)
while True:
mag_x, mag_y, mag_z = sensor.magnetic
print(
"Magnetometer (gauss): ({0:10.3f}, {1:10.3f}, {2:10.3f})".format(
mag_x, mag_y, mag_z
)
)
print("")
time.sleep(1.0)
|
Fast Data Reading Example¶
Fast readings example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | # SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
# SPDX-License-Identifier: MIT
""" Read data from the magnetometer and print it out, ASAP! """
import board
import adafruit_lsm303dlh_mag
i2c = board.I2C() # uses board.SCL and board.SDA
sensor = adafruit_lsm303dlh_mag.LSM303DLH_Mag(i2c)
while True:
mag_x, mag_y, mag_z = sensor.magnetic
print("{0:10.3f} {1:10.3f} {2:10.3f}".format(mag_x, mag_y, mag_z))
|
Compass Example¶
Magnetic compass example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | # SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
# SPDX-License-Identifier: MIT
""" Display compass heading data five times per second """
import time
from math import atan2, degrees
import board
import adafruit_lsm303dlh_mag
i2c = board.I2C() # uses board.SCL and 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)
|