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 DT = COUNT_TIME / 10 # Copmute the color value change per fade steps dr = R_SAND / FADE_STEPS dg = G_SAND / FADE_STEPS db = B_SAND / 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): time.sleep(DT/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: pass # A little debounce time.sleep(0.5) # Wait for Circuit Playground to be flipped back over while cpx.acceleration[2] < 0: pass
Page last edited March 08, 2024
Text editor powered by tinymce.