Simple test
Ensure your device works with this simple test.
examples/lis3dh_simpletest.py
1# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
2# SPDX-License-Identifier: MIT
3
4import time
5
6import board
7import busio
8
9import adafruit_lis3dh
10
11# Hardware I2C setup. Use the CircuitPlayground built-in accelerometer if available;
12# otherwise check I2C pins.
13if hasattr(board, "ACCELEROMETER_SCL"):
14 i2c = busio.I2C(board.ACCELEROMETER_SCL, board.ACCELEROMETER_SDA)
15 lis3dh = adafruit_lis3dh.LIS3DH_I2C(i2c, address=0x19)
16else:
17 i2c = board.I2C() # uses board.SCL and board.SDA
18 # i2c = board.STEMMA_I2C() # For using the built-in STEMMA QT connector on a microcontroller
19 lis3dh = adafruit_lis3dh.LIS3DH_I2C(i2c)
20
21# Hardware SPI setup:
22# spi = board.SPI()
23# cs = digitalio.DigitalInOut(board.D5) # Set to correct CS pin!
24# lis3dh = adafruit_lis3dh.LIS3DH_SPI(spi, cs)
25
26# PyGamer or MatrixPortal I2C Setup:
27# i2c = board.I2C() # uses board.SCL and board.SDA
28# lis3dh = adafruit_lis3dh.LIS3DH_I2C(i2c, address=0x19)
29
30
31# Set range of accelerometer (can be RANGE_2_G, RANGE_4_G, RANGE_8_G or RANGE_16_G).
32lis3dh.range = adafruit_lis3dh.RANGE_2_G
33
34# Loop forever printing accelerometer values
35while True:
36 # Read accelerometer values (in m / s ^ 2). Returns a 3-tuple of x, y,
37 # z axis values. Divide them by 9.806 to convert to Gs.
38 x, y, z = (value / adafruit_lis3dh.STANDARD_GRAVITY for value in lis3dh.acceleration)
39 print(f"x = {x:.3f} G, y = {y:.3f} G, z = {z:.3f} G")
40 # Small delay to keep things responsive but give time for interrupt processing.
41 time.sleep(0.1)
Tap test
Illustrates tap different capabilities
examples/lis3dh_tap.py
1# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
2# SPDX-License-Identifier: MIT
3
4import time
5
6import board
7import busio
8import digitalio
9
10import adafruit_lis3dh
11
12# Hardware I2C setup. Use the CircuitPlayground built-in accelerometer if available;
13# otherwise check I2C pins.
14if hasattr(board, "ACCELEROMETER_SCL"):
15 i2c = busio.I2C(board.ACCELEROMETER_SCL, board.ACCELEROMETER_SDA)
16 int1 = digitalio.DigitalInOut(board.ACCELEROMETER_INTERRUPT)
17 lis3dh = adafruit_lis3dh.LIS3DH_I2C(i2c, address=0x19, int1=int1)
18else:
19 i2c = board.I2C() # uses board.SCL and board.SDA
20 # i2c = board.STEMMA_I2C() # For using the built-in STEMMA QT connector on a microcontroller
21 int1 = digitalio.DigitalInOut(board.D9) # Set this to the correct pin for the interrupt!
22 lis3dh = adafruit_lis3dh.LIS3DH_I2C(i2c, int1=int1)
23
24# Hardware SPI setup:
25# spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
26# cs = digitalio.DigitalInOut(board.D5) # Set to correct CS pin!
27# int1 = digitalio.DigitalInOut(board.D6) # Set to correct pin for interrupt!
28# lis3dh = adafruit_lis3dh.LIS3DH_SPI(spi, cs, int1=int1)
29
30# Set range of accelerometer (can be RANGE_2_G, RANGE_4_G, RANGE_8_G or RANGE_16_G).
31lis3dh.range = adafruit_lis3dh.RANGE_8_G
32
33# Set tap detection to double taps. The first parameter is a value:
34# - 0 = Disable tap detection.
35# - 1 = Detect single taps.
36# - 2 = Detect double taps.
37# The second parameter is the threshold and a higher value means less sensitive
38# tap detection. Note the threshold should be set based on the range above:
39# - 2G = 40-80 threshold
40# - 4G = 20-40 threshold
41# - 8G = 10-20 threshold
42# - 16G = 5-10 threshold
43lis3dh.set_tap(2, 60)
44
45# Loop forever printing if a double tap is detected.
46while True:
47 if lis3dh.tapped:
48 print("Tapped!")
49 time.sleep(0.01)
ADC test
Get the voltage readings
examples/lis3dh_adc.py
1# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
2# SPDX-License-Identifier: MIT
3
4# Analog to digital converter example.
5# Will loop forever printing ADC channel 1 raw and mV values every second.
6# NOTE the ADC can only read voltages in the range of ~900mV to 1800mV!
7
8import time
9
10import board
11import busio
12
13import adafruit_lis3dh
14
15# Uncomment if using SPI
16# import digitalio
17
18
19# Hardware I2C setup. Use the CircuitPlayground built-in accelerometer if available;
20# otherwise check I2C pins.
21if hasattr(board, "ACCELEROMETER_SCL"):
22 i2c = busio.I2C(board.ACCELEROMETER_SCL, board.ACCELEROMETER_SDA)
23 lis3dh = adafruit_lis3dh.LIS3DH_I2C(i2c, address=0x19)
24else:
25 i2c = board.I2C() # uses board.SCL and board.SDA
26 # i2c = board.STEMMA_I2C() # For using the built-in STEMMA QT connector on a microcontroller
27 lis3dh = adafruit_lis3dh.LIS3DH_I2C(i2c)
28
29# Hardware SPI setup:
30# spi = board.SPI()
31# cs = digitalio.DigitalInOut(board.D5) # Set to correct CS pin!
32# lis3dh = adafruit_lis3dh.LIS3DH_SPI(spi, cs)
33
34# PyGamer I2C Setup:
35# i2c = board.I2C(A) # uses board.SCL and board.SDA
36# lis3dh = adafruit_lis3dh.LIS3DH_I2C(i2c, address=0x19)
37
38
39# Loop forever printing ADC readings.
40while True:
41 # Read raw ADC value. Specify which ADC to read: 1, 2, or 3.
42 adc1_raw = lis3dh.read_adc_raw(1)
43 # Or read the ADC value in millivolts:
44 adc1_mV = lis3dh.read_adc_mV(1)
45 print(f"ADC 1 = {adc1_raw} ({adc1_mV} mV)")
46 time.sleep(1)
Spinner Example
Creates a spinner
examples/lis3dh_spinner.py
1# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
2# SPDX-License-Identifier: MIT
3
4# Circuit Playground Express CircuitPython Fidget Spinner
5# This is meant to work with the Circuit Playground Express board:
6# https://www.adafruit.com/product/3333
7# Needs this LIS3DH module and the NeoPixel module installed:
8# https://github.com/adafruit/Adafruit_CircuitPython_LIS3DH
9# https://github.com/adafruit/Adafruit_CircuitPython_NeoPixel
10# Author: Tony DiCola
11# License: MIT License (https://opensource.org/licenses/MIT)
12import math
13import time
14
15import board
16import busio
17import neopixel
18from micropython import const
19
20import adafruit_lis3dh
21
22# Configuration:
23ACCEL_RANGE = adafruit_lis3dh.RANGE_16_G # Accelerometer range.
24TAP_THRESHOLD = 20 # Accelerometer tap threshold. Higher values
25# mean you need to tap harder to start a spin.
26SPINNER_DECAY = 0.5 # Decay rate for the spinner. Set to a value
27# from 0 to 1.0 where lower values mean the
28# spinner slows down faster.
29PRIMARY_COLOR = (0, 255, 0) # Color of the spinner dots.
30SECONDARY_COLOR = (0, 0, 0) # Background color of the spinner.
31
32
33# Define a class that represents the fidget spinner.
34class FidgetSpinner:
35 def __init__(self, decay=0.5):
36 self._decay = decay
37 self._velocity = 0.0
38 self._elapsed = 0.0
39 self._position = 0.0
40
41 def spin(self, velocity):
42 self._velocity = velocity
43 self._elapsed = 0.0
44
45 def get_position(self, delta):
46 # Increment elapsed time and compute the current velocity after a
47 # decay of the initial velocity.
48 self._elapsed += delta
49 current_velocity = self._velocity * math.pow(self._decay, self._elapsed)
50 self._position += current_velocity * delta
51 # Make sure the position stays within values that range from 0 to <10.
52 self._position = math.fmod(self._position, 10.0)
53 if self._position < 0.0:
54 self._position += 10.0
55 return self._position
56
57
58# Initialize NeoPixels and accelerometer.
59pixels = neopixel.NeoPixel(board.NEOPIXEL, 10, auto_write=False)
60pixels.fill((0, 0, 0))
61pixels.show()
62i2c = busio.I2C(board.ACCELEROMETER_SCL, board.ACCELEROMETER_SDA)
63lis3dh = adafruit_lis3dh.LIS3DH_I2C(i2c, address=25)
64
65# Set accelerometer range.
66lis3dh.range = ACCEL_RANGE
67# Enable single click detection, but use a custom CLICK_CFG register value
68# to only detect clicks on the X axis (instead of all 3 X, Y, Z axes).
69lis3dh.set_tap(1, TAP_THRESHOLD, click_cfg=0x01)
70# Enable LIS3DH FIFO in stream mode. This reaches in to the LIS3DH library to
71# call internal methods that change a few register values. This must be done
72# AFTER calling set_tap above because the set_tap function also changes
73# REG_CTRL5.
74# Define register numbers, which are not exported from the library.
75_REG_CTRL5 = const(0x24)
76_REG_CLICKSRC = const(0x39)
77lis3dh._write_register_byte(_REG_CTRL5, 0b01001000)
78lis3dh._write_register_byte(0x2E, 0b10000000) # Set FIFO_CTRL to Stream mode.
79
80# Create a fidget spinner object.
81spinner = FidgetSpinner(SPINNER_DECAY)
82
83
84# Main loop will run forever checking for click/taps from accelerometer and
85# then spinning the spinner.
86last = time.monotonic() # Keep track of the last time the loop ran.
87while True:
88 # Read the raw click detection register value and check if there was
89 # a click detected.
90 clicksrc = lis3dh._read_register_byte(_REG_CLICKSRC)
91 if clicksrc & 0b01000000 > 0:
92 # Click was detected! Quickly read 32 values from the accelerometer
93 # FIFO and look for the maximum magnitude values.
94 maxval = abs(lis3dh.acceleration[0]) # Grab just the X acceleration value.
95 for i in range(31):
96 x = abs(lis3dh.acceleration[0])
97 maxval = max(maxval, x)
98 # Check if this was a positive or negative spin/click event.
99 if clicksrc == 0b1010001:
100 # Positive click, spin in a positive direction.
101 spinner.spin(maxval)
102 elif clicksrc == 0b1011001:
103 # Negative click, spin in negative direction.
104 spinner.spin(-maxval)
105 # Update the amount of time that's passed since the last loop iteration.
106 current = time.monotonic()
107 delta = current - last
108 last = current
109 # Set all pixels to secondary color.
110 pixels.fill(SECONDARY_COLOR)
111 # Update the fidget spinner position and turn on the appropriate pixels.
112 pos = int(spinner.get_position(delta))
113 # Set the current position pixel and the pixel exactly opposite it (i.e. 5
114 # pixels ahead, wrapping back to the start) to the primary color.
115 pixels[pos] = PRIMARY_COLOR
116 pixels[(pos + 5) % 10] = PRIMARY_COLOR
117 pixels.show()
118 # Small delay to stay responsive but give time for interrupt processing.
119 time.sleep(0.05)
Advanced Spinner Example
Creates a spinner with colors and animations
examples/lis3dh_spinner.py
1# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
2# SPDX-License-Identifier: MIT
3
4# Circuit Playground Express CircuitPython Fidget Spinner
5# This is meant to work with the Circuit Playground Express board:
6# https://www.adafruit.com/product/3333
7# Needs this LIS3DH module and the NeoPixel module installed:
8# https://github.com/adafruit/Adafruit_CircuitPython_LIS3DH
9# https://github.com/adafruit/Adafruit_CircuitPython_NeoPixel
10# Author: Tony DiCola
11# License: MIT License (https://opensource.org/licenses/MIT)
12import math
13import time
14
15import board
16import busio
17import neopixel
18from micropython import const
19
20import adafruit_lis3dh
21
22# Configuration:
23ACCEL_RANGE = adafruit_lis3dh.RANGE_16_G # Accelerometer range.
24TAP_THRESHOLD = 20 # Accelerometer tap threshold. Higher values
25# mean you need to tap harder to start a spin.
26SPINNER_DECAY = 0.5 # Decay rate for the spinner. Set to a value
27# from 0 to 1.0 where lower values mean the
28# spinner slows down faster.
29PRIMARY_COLOR = (0, 255, 0) # Color of the spinner dots.
30SECONDARY_COLOR = (0, 0, 0) # Background color of the spinner.
31
32
33# Define a class that represents the fidget spinner.
34class FidgetSpinner:
35 def __init__(self, decay=0.5):
36 self._decay = decay
37 self._velocity = 0.0
38 self._elapsed = 0.0
39 self._position = 0.0
40
41 def spin(self, velocity):
42 self._velocity = velocity
43 self._elapsed = 0.0
44
45 def get_position(self, delta):
46 # Increment elapsed time and compute the current velocity after a
47 # decay of the initial velocity.
48 self._elapsed += delta
49 current_velocity = self._velocity * math.pow(self._decay, self._elapsed)
50 self._position += current_velocity * delta
51 # Make sure the position stays within values that range from 0 to <10.
52 self._position = math.fmod(self._position, 10.0)
53 if self._position < 0.0:
54 self._position += 10.0
55 return self._position
56
57
58# Initialize NeoPixels and accelerometer.
59pixels = neopixel.NeoPixel(board.NEOPIXEL, 10, auto_write=False)
60pixels.fill((0, 0, 0))
61pixels.show()
62i2c = busio.I2C(board.ACCELEROMETER_SCL, board.ACCELEROMETER_SDA)
63lis3dh = adafruit_lis3dh.LIS3DH_I2C(i2c, address=25)
64
65# Set accelerometer range.
66lis3dh.range = ACCEL_RANGE
67# Enable single click detection, but use a custom CLICK_CFG register value
68# to only detect clicks on the X axis (instead of all 3 X, Y, Z axes).
69lis3dh.set_tap(1, TAP_THRESHOLD, click_cfg=0x01)
70# Enable LIS3DH FIFO in stream mode. This reaches in to the LIS3DH library to
71# call internal methods that change a few register values. This must be done
72# AFTER calling set_tap above because the set_tap function also changes
73# REG_CTRL5.
74# Define register numbers, which are not exported from the library.
75_REG_CTRL5 = const(0x24)
76_REG_CLICKSRC = const(0x39)
77lis3dh._write_register_byte(_REG_CTRL5, 0b01001000)
78lis3dh._write_register_byte(0x2E, 0b10000000) # Set FIFO_CTRL to Stream mode.
79
80# Create a fidget spinner object.
81spinner = FidgetSpinner(SPINNER_DECAY)
82
83
84# Main loop will run forever checking for click/taps from accelerometer and
85# then spinning the spinner.
86last = time.monotonic() # Keep track of the last time the loop ran.
87while True:
88 # Read the raw click detection register value and check if there was
89 # a click detected.
90 clicksrc = lis3dh._read_register_byte(_REG_CLICKSRC)
91 if clicksrc & 0b01000000 > 0:
92 # Click was detected! Quickly read 32 values from the accelerometer
93 # FIFO and look for the maximum magnitude values.
94 maxval = abs(lis3dh.acceleration[0]) # Grab just the X acceleration value.
95 for i in range(31):
96 x = abs(lis3dh.acceleration[0])
97 maxval = max(maxval, x)
98 # Check if this was a positive or negative spin/click event.
99 if clicksrc == 0b1010001:
100 # Positive click, spin in a positive direction.
101 spinner.spin(maxval)
102 elif clicksrc == 0b1011001:
103 # Negative click, spin in negative direction.
104 spinner.spin(-maxval)
105 # Update the amount of time that's passed since the last loop iteration.
106 current = time.monotonic()
107 delta = current - last
108 last = current
109 # Set all pixels to secondary color.
110 pixels.fill(SECONDARY_COLOR)
111 # Update the fidget spinner position and turn on the appropriate pixels.
112 pos = int(spinner.get_position(delta))
113 # Set the current position pixel and the pixel exactly opposite it (i.e. 5
114 # pixels ahead, wrapping back to the start) to the primary color.
115 pixels[pos] = PRIMARY_COLOR
116 pixels[(pos + 5) % 10] = PRIMARY_COLOR
117 pixels.show()
118 # Small delay to stay responsive but give time for interrupt processing.
119 time.sleep(0.05)