Skip to content

Commit d16c916

Browse files
authored
Merge pull request #65 from dcbriccetti/accel-maps-pixels
Create an acceleration to LEDs example
2 parents d675c99 + d0d481e commit d16c916

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
"""Maps acceleration (tilt) to Neopixel colors.
2+
3+
x, y, and z acceleration components map to red, green and blue,
4+
respectively.
5+
6+
When the CPX is level, the lights are blue because there is no acceleration
7+
on x or y, but on z, gravity pulls at 9.81 meters per second per second (m/s²).
8+
When banking, the vertical (z) axis is no longer directly aligned with gravity,
9+
so the blue decreases, and red increases because gravity is now pulling more
10+
along the x axis. Similarly, when changing the pitch from level, we see blue change
11+
to green.
12+
13+
This video walks you through the code: https://youtu.be/eNpPLbYx-iA
14+
"""
15+
16+
import time
17+
from adafruit_circuitplayground.express import cpx
18+
19+
cpx.pixels.brightness = 0.2 # Adjust overall brightness as desired, between 0 and 1
20+
21+
22+
def color_amount(accel_component):
23+
"""Convert acceleration component (x, y, or z) to color amount (r, g, or b)"""
24+
standard_gravity = 9.81 # Acceleration (m/s²) due to gravity at the earth’s surface
25+
accel_magnitude = abs(accel_component) # Ignore the direction
26+
constrained_accel = min(accel_magnitude, standard_gravity) # Constrain values
27+
normalized_accel = constrained_accel / standard_gravity # Convert to 0–1
28+
return round(normalized_accel * 255) # Convert to 0–255
29+
30+
31+
def format_acceleration():
32+
return ', '.join(('{:>6.2f}'.format(axis_value) for axis_value in acceleration))
33+
34+
35+
def format_rgb():
36+
return ', '.join(('{:>3d}'.format(rgb_amount) for rgb_amount in rgb_amounts))
37+
38+
39+
def log_values():
40+
print('({}) ==> ({})'.format(format_acceleration(), format_rgb()))
41+
42+
43+
while True:
44+
acceleration = cpx.acceleration
45+
rgb_amounts = [color_amount(axis_value) for axis_value in acceleration]
46+
cpx.pixels.fill(rgb_amounts)
47+
log_values()
48+
time.sleep(0.1)

0 commit comments

Comments
 (0)