Skip to content

Commit f870d33

Browse files
committed
Create code.py
1 parent 8af3cec commit f870d33

File tree

1 file changed

+92
-0
lines changed

1 file changed

+92
-0
lines changed

Head_in_a_Jar/code.py

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
"""
2+
Circuit Playground Express shake trigger.
3+
4+
Reads accelerometer magnitude and, when it exceeds SHAKE_THRESHOLD,
5+
pulses pin A1 HIGH for TRIGGER_DURATION seconds, then enforces a cooldown.
6+
7+
Also sets a fixed NeoPixel pattern at startup.
8+
"""
9+
10+
import math
11+
import time
12+
13+
import board
14+
import digitalio
15+
from adafruit_circuitplayground.express import cpx
16+
17+
SHAKE_THRESHOLD = 11.0
18+
TRIGGER_DURATION = 3.0 # seconds
19+
COOLDOWN = 1.0 # seconds to wait after trigger
20+
LOOP_DELAY = 0.01 # seconds
21+
22+
23+
def setup_a1_output() -> digitalio.DigitalInOut:
24+
"""Configure A1 as a digital output, default LOW."""
25+
a1_output = digitalio.DigitalInOut(board.A1)
26+
a1_output.direction = digitalio.Direction.OUTPUT
27+
a1_output.value = False
28+
return a1_output
29+
30+
31+
def set_pixel_pattern() -> None:
32+
"""Set the NeoPixel ring to a red/green pattern."""
33+
red = (255, 0, 0)
34+
green = (0, 255, 0)
35+
36+
pattern = (
37+
red, red, red, # 0-2
38+
green, green, # 3-4
39+
red, red, red, # 5-7
40+
green, green, # 8-9
41+
)
42+
43+
cpx.pixels.auto_write = False
44+
# Adjust to taste; helps battery + brightness.
45+
cpx.pixels.brightness = 0.2
46+
47+
for index, color in enumerate(pattern):
48+
cpx.pixels[index] = color
49+
50+
cpx.pixels.show()
51+
52+
53+
def acceleration_magnitude() -> float:
54+
"""Return the magnitude of the CPX acceleration vector."""
55+
accel_x, accel_y, accel_z = cpx.acceleration
56+
return math.sqrt((accel_x ** 2) + (accel_y ** 2) + (accel_z ** 2))
57+
58+
59+
def pulse(output: digitalio.DigitalInOut, duration_s: float) -> None:
60+
"""Set output HIGH for duration_s seconds, then LOW."""
61+
output.value = True
62+
time.sleep(duration_s)
63+
output.value = False
64+
65+
66+
def main() -> None:
67+
"""Main loop."""
68+
a1_pin = setup_a1_output()
69+
set_pixel_pattern()
70+
71+
while True:
72+
magnitude = acceleration_magnitude()
73+
74+
print(
75+
f"Magnitude: {magnitude:.2f} | "
76+
f"Threshold: {SHAKE_THRESHOLD:.2f} | "
77+
f"A1 value: {a1_pin.value}"
78+
)
79+
80+
if magnitude > SHAKE_THRESHOLD:
81+
print(">>> SHAKE DETECTED! Pulsing A1 HIGH")
82+
a1_pin.value = True
83+
print(f"A1 is now: {a1_pin.value}")
84+
time.sleep(TRIGGER_DURATION)
85+
a1_pin.value = False
86+
print(f"A1 is now: {a1_pin.value}")
87+
time.sleep(COOLDOWN)
88+
89+
time.sleep(LOOP_DELAY)
90+
91+
92+
main()

0 commit comments

Comments
 (0)