Skip to content

Commit ab7effe

Browse files
authored
Merge pull request #13 from dmolavi/master
Add SparklePulse animation
2 parents 04f0dce + 19a93cd commit ab7effe

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

adafruit_led_animation/animation.py

+53
Original file line numberDiff line numberDiff line change
@@ -386,6 +386,59 @@ def draw(self):
386386
self.fill(color)
387387
self.show()
388388

389+
class SparklePulse(Animation):
390+
"""
391+
Combination of the Spark and Pulse animations.
392+
393+
:param pixel_object: The initialised LED object.
394+
:param int speed: Animation refresh rate in seconds, e.g. ``0.1``.
395+
:param color: Animation color in ``(r, g, b)`` tuple, or ``0x000000`` hex format.
396+
:param period: Period to pulse the LEDs over. Default 5.
397+
:param max_intensity: The maximum intensity to pulse, between 0 and 1.0. Default 1.
398+
:param min_intensity: The minimum intensity to pulse, between 0 and 1.0. Default 0.
399+
"""
400+
401+
# pylint: disable=too-many-arguments
402+
def __init__(self, pixel_object, speed, color, period=5, max_intensity=1, min_intensity=0):
403+
if len(pixel_object) < 2:
404+
raise ValueError("Sparkle needs at least 2 pixels")
405+
self.max_intensity = max_intensity
406+
self.min_intensity = min_intensity
407+
self._period = period
408+
self._intensity_delta = max_intensity - min_intensity
409+
self._half_period = period / 2
410+
self._position_factor = 1 / self._half_period
411+
self._bpp = len(pixel_object[0])
412+
self._last_update = monotonic_ns()
413+
self._cycle_position = 0
414+
self._half_color = None
415+
self._dim_color = None
416+
super(SparklePulse, self).__init__(pixel_object, speed, color)
417+
418+
def _recompute_color(self, color):
419+
half_color = tuple(color[rgb] // 4 for rgb in range(len(color)))
420+
dim_color = tuple(color[rgb] // 10 for rgb in range(len(color)))
421+
for pixel in range(len(self.pixel_object)):
422+
if self.pixel_object[pixel] == self._half_color:
423+
self.pixel_object[pixel] = half_color
424+
elif self.pixel_object[pixel] == self._dim_color:
425+
self.pixel_object[pixel] = dim_color
426+
self._half_color = half_color
427+
self._dim_color = dim_color
428+
429+
def draw(self):
430+
pixel = random.randint(0, (len(self.pixel_object) - 2))
431+
432+
now = monotonic_ns()
433+
time_since_last_draw = (now - self._last_update) / NANOS_PER_SECOND
434+
self._last_update = now
435+
pos = self._cycle_position = (self._cycle_position + time_since_last_draw) % self._period
436+
if pos > self._half_period:
437+
pos = self._period - pos
438+
intensity = self.min_intensity + (pos * self._intensity_delta * self._position_factor)
439+
color = [int(self.color[n] * intensity) for n in range(self._bpp)]
440+
self.pixel_object[pixel] = color
441+
self.show()
389442

390443
class Chase(Animation):
391444
"""

0 commit comments

Comments
 (0)