Skip to content

Commit 17faa95

Browse files
committed
use a sine wave and time based positioning
1 parent 072aad6 commit 17faa95

File tree

1 file changed

+13
-13
lines changed

1 file changed

+13
-13
lines changed

adafruit_led_animation/animation.py

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ def monotonic_ns():
5555
return int(time.time() * 1000000000)
5656

5757
import random
58-
from math import ceil, sin
58+
from math import ceil, sin, radians
5959
from .color import BLACK, RAINBOW
6060

6161
__version__ = "0.0.0-auto.0"
@@ -354,24 +354,24 @@ class Pulse(Animation):
354354

355355
# pylint: disable=too-many-arguments
356356
def __init__(self, pixel_object, speed, color, period=5, max_intensity=1, min_intensity=0):
357-
self._intensity = min_intensity
358357
self.max_intensity = max_intensity
359358
self.min_intensity = min_intensity
360-
self._direction = 1.0
361-
# TODO Fix this:
362-
self._intensity_step = 2 / (period / speed)
359+
self._period = period
360+
self._intensity_delta = max_intensity - min_intensity
361+
self._radians_per_second = radians(180 / period)
363362
self._bpp = len(pixel_object[0])
363+
self._last_update = monotonic_ns()
364+
self._cycle_position = 0
364365
super(Pulse, self).__init__(pixel_object, speed, color)
365366

366367
def draw(self):
367-
self._intensity += self._intensity_step * self._direction
368-
if self._direction < 0 and self._intensity <= self.min_intensity:
369-
self._direction = -self._direction
370-
self._intensity = self.min_intensity
371-
elif self._direction > 0 and self._intensity >= self.max_intensity:
372-
self._direction = -self._direction
373-
self._intensity = self.max_intensity
374-
color = [int(self._color[n] * self._intensity) for n in range(self._bpp)]
368+
now = monotonic_ns()
369+
time_since_last_draw = (now - self._last_update) / 1000000000
370+
self._last_update = now
371+
self._cycle_position = (self._cycle_position + time_since_last_draw) % self._period
372+
intensity = self.min_intensity + (sin(self._radians_per_second * self._cycle_position) * self._intensity_delta)
373+
374+
color = [int(self._color[n] * intensity) for n in range(self._bpp)]
375375
self.fill(color)
376376
self.show()
377377

0 commit comments

Comments
 (0)