Skip to content

Added shake detection #13

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Nov 27, 2017
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions adafruit_lis3dh/lis3dh.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
import ustruct as struct

from micropython import const
import time
import math

# Register addresses:
REG_OUTADC1_L = const(0x08)
Expand Down Expand Up @@ -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):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please put the internal explanation here after a #. The """ comment should only have the "public" info.

# 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.
Expand Down