diff --git a/adafruit_lis3dh/lis3dh.py b/adafruit_lis3dh/lis3dh.py index 2bef3e0..205602c 100755 --- a/adafruit_lis3dh/lis3dh.py +++ b/adafruit_lis3dh/lis3dh.py @@ -9,6 +9,8 @@ import ustruct as struct from micropython import const +import time +import math # Register addresses: REG_OUTADC1_L = const(0x08) @@ -113,6 +115,33 @@ def acceleration(self): return (x / divider * 9.806, y / divider * 9.806, z / divider * 9.806) + def shake(self, shake_threshold=30, avg_count=10, total_delay=0.1): + """Detect when the accelerometer is shaken. Optional parameters: + shake_threshold - Increase or decrease to change shake sensitivity. This + requires a minimum value of 10. 10 is the total + acceleration if the board is not moving, therefore + anything less than 10 will erroneously report a constant + shake detected. (Default 30) + avg_count - The number of readings taken and used for the average + acceleration. (Default 10) + total_delay - The total time in seconds it takes to obtain avg_count + readings from acceleration. (Default 0.1) + """ + shake_accel = (0, 0, 0) + for i in range(avg_count): + # shake_accel creates a list of tuples from acceleration data. + # zip takes multiple tuples and zips them together, as in: + # In : zip([-0.2, 0.0, 9.5], [37.9, 13.5, -72.8]) + # Out: [(-0.2, 37.9), (0.0, 13.5), (9.5, -72.8)] + # map applies sum to each member of this tuple, resulting in a + # 3-member list. tuple converts this list into a tuple which is + # used as shake_accel. + shake_accel = tuple(map(sum, zip(shake_accel, self.acceleration))) + time.sleep(total_delay / avg_count) + avg = tuple(value / avg_count for value in shake_accel) + total_accel = math.sqrt(sum(map(lambda x: x * x, avg))) + return total_accel > shake_threshold + def read_adc_raw(self, adc): """Retrieve the raw analog to digital converter value. ADC must be a value 1, 2, or 3.