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