Skip to content

Commit 8a7d9d9

Browse files
kattnitannewt
authored andcommitted
Added shake detection (#13)
1 parent 2a476ae commit 8a7d9d9

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

adafruit_lis3dh/lis3dh.py

+29
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@
99
import ustruct as struct
1010

1111
from micropython import const
12+
import time
13+
import math
1214

1315
# Register addresses:
1416
REG_OUTADC1_L = const(0x08)
@@ -113,6 +115,33 @@ def acceleration(self):
113115

114116
return (x / divider * 9.806, y / divider * 9.806, z / divider * 9.806)
115117

118+
def shake(self, shake_threshold=30, avg_count=10, total_delay=0.1):
119+
"""Detect when the accelerometer is shaken. Optional parameters:
120+
shake_threshold - Increase or decrease to change shake sensitivity. This
121+
requires a minimum value of 10. 10 is the total
122+
acceleration if the board is not moving, therefore
123+
anything less than 10 will erroneously report a constant
124+
shake detected. (Default 30)
125+
avg_count - The number of readings taken and used for the average
126+
acceleration. (Default 10)
127+
total_delay - The total time in seconds it takes to obtain avg_count
128+
readings from acceleration. (Default 0.1)
129+
"""
130+
shake_accel = (0, 0, 0)
131+
for i in range(avg_count):
132+
# shake_accel creates a list of tuples from acceleration data.
133+
# zip takes multiple tuples and zips them together, as in:
134+
# In : zip([-0.2, 0.0, 9.5], [37.9, 13.5, -72.8])
135+
# Out: [(-0.2, 37.9), (0.0, 13.5), (9.5, -72.8)]
136+
# map applies sum to each member of this tuple, resulting in a
137+
# 3-member list. tuple converts this list into a tuple which is
138+
# used as shake_accel.
139+
shake_accel = tuple(map(sum, zip(shake_accel, self.acceleration)))
140+
time.sleep(total_delay / avg_count)
141+
avg = tuple(value / avg_count for value in shake_accel)
142+
total_accel = math.sqrt(sum(map(lambda x: x * x, avg)))
143+
return total_accel > shake_threshold
144+
116145
def read_adc_raw(self, adc):
117146
"""Retrieve the raw analog to digital converter value. ADC must be a
118147
value 1, 2, or 3.

0 commit comments

Comments
 (0)