|
9 | 9 | import ustruct as struct
|
10 | 10 |
|
11 | 11 | from micropython import const
|
| 12 | +import time |
| 13 | +import math |
12 | 14 |
|
13 | 15 | # Register addresses:
|
14 | 16 | REG_OUTADC1_L = const(0x08)
|
@@ -113,6 +115,33 @@ def acceleration(self):
|
113 | 115 |
|
114 | 116 | return (x / divider * 9.806, y / divider * 9.806, z / divider * 9.806)
|
115 | 117 |
|
| 118 | + def shake(self, shake_threshold=30, avg_count=10, total_delay=0.1): |
| 119 | + """Detect when the accelerometer is shaken. Optional parameters: |
| 120 | + shake_threshold - Increase or decrease to change shake sensitivity. This |
| 121 | + requires a minimum value of 10. 10 is the total |
| 122 | + acceleration if the board is not moving, therefore |
| 123 | + anything less than 10 will erroneously report a constant |
| 124 | + shake detected. (Default 30) |
| 125 | + avg_count - The number of readings taken and used for the average |
| 126 | + acceleration. (Default 10) |
| 127 | + total_delay - The total time in seconds it takes to obtain avg_count |
| 128 | + readings from acceleration. (Default 0.1) |
| 129 | + """ |
| 130 | + shake_accel = (0, 0, 0) |
| 131 | + for i in range(avg_count): |
| 132 | + # shake_accel creates a list of tuples from acceleration data. |
| 133 | + # zip takes multiple tuples and zips them together, as in: |
| 134 | + # In : zip([-0.2, 0.0, 9.5], [37.9, 13.5, -72.8]) |
| 135 | + # Out: [(-0.2, 37.9), (0.0, 13.5), (9.5, -72.8)] |
| 136 | + # map applies sum to each member of this tuple, resulting in a |
| 137 | + # 3-member list. tuple converts this list into a tuple which is |
| 138 | + # used as shake_accel. |
| 139 | + shake_accel = tuple(map(sum, zip(shake_accel, self.acceleration))) |
| 140 | + time.sleep(total_delay / avg_count) |
| 141 | + avg = tuple(value / avg_count for value in shake_accel) |
| 142 | + total_accel = math.sqrt(sum(map(lambda x: x * x, avg))) |
| 143 | + return total_accel > shake_threshold |
| 144 | + |
116 | 145 | def read_adc_raw(self, adc):
|
117 | 146 | """Retrieve the raw analog to digital converter value. ADC must be a
|
118 | 147 | value 1, 2, or 3.
|
|
0 commit comments