Skip to content

Commit 13f1648

Browse files
authored
Merge pull request #3202 from firepixie/Head_in_a_Jar
Code for Head in a Jar
2 parents 8af3cec + 2850a87 commit 13f1648

File tree

1 file changed

+88
-0
lines changed

1 file changed

+88
-0
lines changed

Head_in_a_Jar/code.py

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

0 commit comments

Comments
 (0)