Skip to content

Commit 4e746e1

Browse files
committed
Add SparklePulse animation
1 parent ec398cf commit 4e746e1

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

adafruit_led_animation/animation.py

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -367,6 +367,57 @@ def draw(self):
367367
self.fill(color)
368368
self.show()
369369

370+
class SparklePulse(Animation):
371+
"""
372+
Combination of the Spark and Pulse animations.
373+
374+
:param pixel_object: The initialised LED object.
375+
:param int speed: Animation refresh rate in seconds, e.g. ``0.1``.
376+
:param color: Animation color in ``(r, g, b)`` tuple, or ``0x000000`` hex format.
377+
:param period: Period to pulse the LEDs over. Default 5.
378+
:param max_intensity: The maximum intensity to pulse, between 0 and 1.0. Default 1.
379+
:param min_intensity: The minimum intensity to pulse, between 0 and 1.0. Default 0.
380+
"""
381+
def __init__(self, pixel_object, speed, color, period=5, max_intensity=1, min_intensity=0):
382+
if len(pixel_object) < 2:
383+
raise ValueError("Sparkle needs at least 2 pixels")
384+
self.max_intensity = max_intensity
385+
self.min_intensity = min_intensity
386+
self._period = period
387+
self._intensity_delta = max_intensity - min_intensity
388+
self._half_period = period / 2
389+
self._position_factor = 1 / self._half_period
390+
self._bpp = len(pixel_object[0])
391+
self._last_update = monotonic_ns()
392+
self._cycle_position = 0
393+
self._half_color = None
394+
self._dim_color = None
395+
super(SparklePulse, self).__init__(pixel_object, speed, color)
396+
397+
def _recompute_color(self, color):
398+
half_color = tuple(color[rgb] // 4 for rgb in range(len(color)))
399+
dim_color = tuple(color[rgb] // 10 for rgb in range(len(color)))
400+
for pixel in range(len(self.pixel_object)):
401+
if self.pixel_object[pixel] == self._half_color:
402+
self.pixel_object[pixel] = half_color
403+
elif self.pixel_object[pixel] == self._dim_color:
404+
self.pixel_object[pixel] = dim_color
405+
self._half_color = half_color
406+
self._dim_color = dim_color
407+
408+
def draw(self):
409+
pixel = random.randint(0, (len(self.pixel_object) - 2))
410+
411+
now = monotonic_ns()
412+
time_since_last_draw = (now - self._last_update) / NANOS_PER_SECOND
413+
self._last_update = now
414+
pos = self._cycle_position = (self._cycle_position + time_since_last_draw) % self._period
415+
if pos > self._half_period:
416+
pos = self._period - pos
417+
intensity = self.min_intensity + (pos * self._intensity_delta * self._position_factor)
418+
color = [int(self.color[n] * intensity) for n in range(self._bpp)]
419+
self.pixel_object[pixel] = color
420+
self.show()
370421

371422
class Chase(Animation):
372423
"""

0 commit comments

Comments
 (0)