|
| 1 | +# SPDX-FileCopyrightText: 2025 Jose D. Montoya |
| 2 | +# SPDX-License-Identifier: MIT |
| 3 | + |
| 4 | +# This example simulates a ball bouncing on a NeoPixel strip affected by gravity. |
| 5 | +# Most NeoPixels = neopixel.GRB or neopixel.GRBW |
| 6 | +# The 8mm Diffused NeoPixel (PID 1734) = neopixel.RGB |
| 7 | +import time |
| 8 | +import board |
| 9 | +import neopixel |
| 10 | +from math import ceil |
| 11 | + |
| 12 | +# Configure the setup |
| 13 | +PIXEL_PIN = board.A3 # pin that the NeoPixel is connected to |
| 14 | +ORDER = neopixel.RGB # pixel color channel order |
| 15 | +COLOR = (255, 50, 150) # color to blink |
| 16 | +CLEAR = (0, 0, 0) # clear (or second color) |
| 17 | +DELAY = 0.1 # blink rate in seconds |
| 18 | + |
| 19 | +# Simulation Values. |
| 20 | +gravity = 0.5 |
| 21 | +velocity = 2 |
| 22 | +energy_loss = 0.6 |
| 23 | + |
| 24 | +# Create the NeoPixel object |
| 25 | +num_pixels = 60 |
| 26 | +pixel_seg = neopixel.NeoPixel(PIXEL_PIN, num_pixels, pixel_order=ORDER) |
| 27 | + |
| 28 | +# Animation start values |
| 29 | +travel = 0 |
| 30 | +going_up = False |
| 31 | +floor_count = 0 |
| 32 | +top = 0 |
| 33 | + |
| 34 | +# Loop forever and simulate |
| 35 | +while True: |
| 36 | + # Blink the color |
| 37 | + pixel_seg[travel] = COLOR |
| 38 | + time.sleep(0.05) |
| 39 | + pixel_seg[travel] = CLEAR |
| 40 | + time.sleep(DELAY) |
| 41 | + velocity += gravity |
| 42 | + |
| 43 | + # Check if the ball is at the top to change direction |
| 44 | + if velocity >= 0 and going_up: |
| 45 | + velocity = ceil(-velocity) |
| 46 | + going_up = False |
| 47 | + top = travel |
| 48 | + |
| 49 | + # Check if the ball is at the bottom to break the loop |
| 50 | + if top == num_pixels - 1: |
| 51 | + floor_count = floor_count + 1 |
| 52 | + if floor_count == 3: |
| 53 | + break |
| 54 | + |
| 55 | + travel = int(travel + velocity) |
| 56 | + |
| 57 | + # Check if the ball is at the floor to change direction |
| 58 | + if travel >= num_pixels: |
| 59 | + travel = num_pixels - 1 |
| 60 | + velocity = ceil(-velocity * energy_loss) |
| 61 | + going_up = True |
| 62 | + |
| 63 | +# Clear the strip |
| 64 | +pixel_seg.fill(0) |
0 commit comments