Skip to content

Commit a9d5a97

Browse files
committed
More explicitly control the mapping between acceleration and RGB
1 parent 999ca3c commit a9d5a97

File tree

1 file changed

+14
-3
lines changed

1 file changed

+14
-3
lines changed

examples/circuitplayground_acceleration_neopixels.py

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44
values to light up the NeoPixels based on those acceleration values."""
55
from adafruit_circuitplayground.express import cpx
66

7+
cpx.pixels.brightness = 0.2 # Adjust as desired, between 0 and 1
8+
79
# Main loop gets x, y and z axis acceleration, prints the values, and turns on
810
# red, green and blue, at levels related to the x, y and z values.
911
while True:
@@ -13,6 +15,15 @@
1315
cpx.pixels.fill((0, 0, 0))
1416
continue
1517
else:
16-
x, y, z = cpx.acceleration
17-
print((x, y, z))
18-
cpx.pixels.fill((abs(int(x)), abs(int(y)), abs(int(z))))
18+
def color_amount(accel_component):
19+
"""Convert acceleration component (x, y, or z) to color amount (r, g, or b)"""
20+
standard_gravity = 9.81 # Acceleration (m/s²) due to gravity at the earth’s surface
21+
accel_magnitude = abs(accel_component) # Ignore the direction
22+
constrained_accel = min(accel_magnitude, standard_gravity) # Constrain values to standard gravity
23+
normalized_accel = constrained_accel / standard_gravity # Convert to a number between 0 and 1
24+
return round(normalized_accel * 255) # Scale to RGB range of 0–255
25+
26+
acceleration = [round(a, 2) for a in cpx.acceleration] # Get the acceleration and reduce the precision
27+
rgb_amounts = tuple(map(color_amount, acceleration)) # Call color_amount for each acceleration part
28+
print(acceleration, '->', rgb_amounts) # Print the acceleration and corresponding RGB values
29+
cpx.pixels.fill(rgb_amounts) # Light the pixels

0 commit comments

Comments
 (0)