@@ -357,6 +357,34 @@ def were_pressed(self):
357
357
ret .add (button )
358
358
return ret
359
359
360
+ def shake (self , shake_threshold = 30 , avg_count = 10 , total_delay = 0.1 ):
361
+ """
362
+ Detect when the accelerometer is shaken. Optional parameters:
363
+ :param shake_threshold: Increase or decrease to change shake sensitivity. This
364
+ requires a minimum value of 10. 10 is the total
365
+ acceleration if the board is not moving, therefore
366
+ anything less than 10 will erroneously report a constant
367
+ shake detected. (Default 30)
368
+ :param avg_count: The number of readings taken and used for the average
369
+ acceleration. (Default 10)
370
+ :param total_delay: The total time in seconds it takes to obtain avg_count
371
+ readings from acceleration. (Default 0.1)
372
+ """
373
+ shake_accel = (0 , 0 , 0 )
374
+ for _ in range (avg_count ):
375
+ # shake_accel creates a list of tuples from acceleration data.
376
+ # zip takes multiple tuples and zips them together, as in:
377
+ # In : zip([-0.2, 0.0, 9.5], [37.9, 13.5, -72.8])
378
+ # Out: [(-0.2, 37.9), (0.0, 13.5), (9.5, -72.8)]
379
+ # map applies sum to each member of this tuple, resulting in a
380
+ # 3-member list. tuple converts this list into a tuple which is
381
+ # used as shake_accel.
382
+ shake_accel = tuple (map (sum , zip (shake_accel , self .acceleration )))
383
+ time .sleep (total_delay / avg_count )
384
+ avg = tuple (value / avg_count for value in shake_accel )
385
+ total_accel = math .sqrt (sum (map (lambda x : x * x , avg )))
386
+ return total_accel > shake_threshold
387
+
360
388
@property
361
389
def acceleration (self ):
362
390
"""Obtain acceleration data from the x, y and z axes.
0 commit comments