Simple tests
Ensure your device works with these simple tests.
examples/lsm303_simpletest.py
1# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
2# SPDX-License-Identifier: MIT
3
4"""Display accelerometer data once per second"""
5
6import time
7
8import board
9
10import adafruit_lsm303_accel
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_lsm303_accel.LSM303_Accel(i2c)
15
16while True:
17 acc_x, acc_y, acc_z = sensor.acceleration
18
19 print(f"Acceleration (m/s^2): ({acc_x:10.3f}, {acc_y:10.3f}, {acc_z:10.3f})")
20 print("")
21 time.sleep(1.0)
Fast Acceleration Example
Example to demonstrate fast acceleration data acquisition
examples/lsm303_fast_accel.py
1# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
2# SPDX-License-Identifier: MIT
3
4"""Read data from the accelerometer and print it out, ASAP!"""
5
6import board
7
8import adafruit_lsm303_accel
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_lsm303_accel.LSM303_Accel(i2c)
13
14while True:
15 accel_x, accel_y, accel_z = sensor.acceleration
16 print(f"{accel_x:10.3f} {accel_y:10.3f} {accel_z:10.3f}")
Inclinometer Example
Demonstrate inclinometer example
examples/lsm303_accel_inclinometer.py
1# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
2# SPDX-License-Identifier: MIT
3
4"""Display inclination data five times per second"""
5
6import time
7from math import atan2, degrees
8
9import board
10
11import adafruit_lsm303_accel
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_lsm303_accel.LSM303_Accel(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_inclination(_sensor):
26 x, y, z = _sensor.acceleration
27 return vector_2_degrees(x, z), vector_2_degrees(y, z)
28
29
30while True:
31 angle_xz, angle_yz = get_inclination(sensor)
32 print(f"XZ angle = {angle_xz:6.2f}deg YZ angle = {angle_yz:6.2f}deg")
33 time.sleep(0.2)
Tap Detection Example
Tap detection example
examples/lsm303_accel_tap_detection.py
1# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
2# SPDX-License-Identifier: MIT
3
4import board
5
6import adafruit_lsm303_accel
7
8i2c = board.I2C() # uses board.SCL and board.SDA
9# i2c = board.STEMMA_I2C() # For using the built-in STEMMA QT connector on a microcontroller
10accel = adafruit_lsm303_accel.LSM303_Accel(i2c)
11accel.range = adafruit_lsm303_accel.Range.RANGE_8G
12accel.set_tap(1, 30)
13
14while True:
15 if accel.tapped:
16 print("Tapped!\n")