code.py
1 # SPDX-FileCopyrightText: 2018 Kattni Rembor for Adafruit Industries 2 # 3 # SPDX-License-Identifier: MIT 4 5 import time 6 from rainbowio import colorwheel 7 from adafruit_circuitplayground.express import cpx 8 9 10 # pylint: disable=redefined-outer-name 11 def upright(x, y, z): 12 return abs(x) < accel_threshold \ 13 and abs(y) < accel_threshold \ 14 and abs(9.8 - z) < accel_threshold 15 16 17 def right_side(x, y, z): 18 return abs(-9.8 - x) < accel_threshold \ 19 and abs(y) < accel_threshold \ 20 and abs(z) < accel_threshold 21 22 23 def left_side(x, y, z): 24 return abs(9.8 - x) < accel_threshold \ 25 and abs(y) < accel_threshold \ 26 and abs(z) < accel_threshold 27 28 29 # pylint: enable=redefined-outer-name 30 31 32 def cycle_sequence(seq): 33 while True: 34 for elem in seq: 35 yield elem 36 37 38 def rainbow_lamp(seq): 39 g = cycle_sequence(seq) 40 while True: 41 # pylint: disable=stop-iteration-return 42 cpx.pixels.fill(colorwheel(next(g))) 43 yield 44 45 46 def brightness_lamp(): 47 brightness_value = cycle_sequence([0.4, 0.6, 0.8, 1, 0.2]) 48 while True: 49 # pylint: disable=stop-iteration-return 50 cpx.pixels.brightness = next(brightness_value) 51 yield 52 53 54 color_sequences = cycle_sequence([ 55 range(256), # rainbow_cycle 56 [0], # red 57 [10], # orange 58 [30], # yellow 59 [85], # green 60 [137], # cyan 61 [170], # blue 62 [213], # purple 63 [0, 10, 30, 85, 137, 170, 213], # party mode 64 ]) 65 66 heart_rates = cycle_sequence([0, 0.5, 1.0]) 67 68 brightness = brightness_lamp() 69 70 heart_rate = 0 71 last_heart_beat = time.monotonic() 72 next_heart_beat = last_heart_beat + heart_rate 73 74 rainbow = None 75 state = None 76 hold_end = None 77 78 cpx.detect_taps = 2 79 accel_threshold = 2 80 cpx.pixels.brightness = 0.2 81 hold_time = 1 82 83 while True: 84 now = time.monotonic() 85 x, y, z = cpx.acceleration 86 87 if left_side(x, y, z): 88 if state is None or not state.startswith("left"): 89 hold_end = now + hold_time 90 state = "left" 91 elif (state == "left" 92 and hold_end is not None 93 and now >= hold_end): 94 state = "left-done" 95 next(brightness) 96 elif right_side(x, y, z): 97 if state is None or not state.startswith("right"): 98 hold_end = now + hold_time 99 state = "right" 100 elif (state == "right" 101 and hold_end is not None 102 and now >= hold_end): 103 state = "right-done" 104 heart_rate = next(heart_rates) 105 last_heart_beat = now 106 next_heart_beat = last_heart_beat + heart_rate 107 elif upright(x, y, z): 108 if state != "upright": 109 hold_end = None 110 state = "upright" 111 112 if cpx.tapped or rainbow is None: 113 rainbow = rainbow_lamp(next(color_sequences)) 114 115 if now >= next_heart_beat: 116 next(rainbow) 117 last_heart_beat = now 118 next_heart_beat = last_heart_beat + heart_rate 119 120 if cpx.shake(shake_threshold=20): 121 cpx.pixels.brightness = 0