Skip to content

Add shake #20

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 2 commits into from
Feb 26, 2020
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
31 changes: 31 additions & 0 deletions adafruit_clue.py
Original file line number Diff line number Diff line change
Expand Up @@ -357,6 +357,37 @@ def were_pressed(self):
ret.add(button)
return ret

def shake(self, shake_threshold=30, avg_count=10, total_delay=0.1):
"""
Detect when the accelerometer is shaken. Optional parameters:

:param 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)

:param avg_count: The number of readings taken and used for the average
acceleration. (Default 10)

:param 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 _ 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

@property
def acceleration(self):
"""Obtain acceleration data from the x, y and z axes.
Expand Down