Our previous code simply waited at each NeoPixel the computed amount of time DT, and then turned the NeoPixel off. Now let's change things so that the NeoPixel fades out over this period of time.

Basically, we need to go one level deeper on our time line. Now, within each time slice DT, instead of doing nothing, we'll be fading the NeoPixel. See the figure below.

The value N is just an arbitrary number of steps over which the fading will occur. This further divides the time slice DT into smaller slices, called FADE_DT in the figure above.

The simplest way to fade a NeoPixel is to linearly change the setting from its starting value down to zero. The NeoPixels on the Circuit Playground have red, green, and blue LEDs in them, so we do the same thing for each of the color components individually. This idea is shown in the figure below.

So at each of the fading time steps, we decrease the red, green, and blue values by a small amount. After doing this N times, the values will reach 0.

OK, here's our final code, with flip-to-reset and fading NeoPixel grains of sand.

# Circuit Playground Express Fading Hourglass
# Author: Carter Nelson
# MIT License (https://opensource.org/licenses/MIT)
import time
from adafruit_circuitplayground.express import cpx

# Make less bright (not blinding!)
cpx.pixels.brightness = 0.2

COUNT_TIME      = 30  # seconds
FADE_STEPS      = 100 # NeoPixel fade steps
R_SAND          = 255 # Sand color RED value
G_SAND          = 255 # Sand color GREEN value
B_SAND          = 255 # Sand color BLUE value

# Compute per NeoPixel wait time

# Copmute the color value change per fade steps

while True:
    # Turn ON all the NeoPixels
    cpx.pixels.fill((R_SAND, G_SAND, B_SAND))
    # Loop over each NeoPixel
    for p in range(10):
        # Set the start RGB values
        r = R_SAND
        g = G_SAND
        b = B_SAND
        # Loop over each fading steps
        for n in range(FADE_STEPS):
            r = r - dr;
            g = g - dg;
            b = b - db;
            cpx.pixels[p] = (int(r),int(g),int(b))
    # Wait for Circuit Playground to be flipped over
    while cpx.acceleration[2] > 0:
    # A little debounce
    # Wait for Circuit Playground to be flipped back over
    while cpx.acceleration[2] < 0:

This guide was first published on Dec 29, 2016. It was last updated on Nov 17, 2017.

This page (Fading Hourglass) was last updated on Nov 17, 2017.

Text editor powered by tinymce.