larson_hue.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # Copyright (c) 2017-18 Richard Hull and contributors
  4. # See LICENSE.rst for details.
  5. #
  6. # Based on https://github.com/pimoroni/blinkt/blob/master/examples/larson_hue.py
  7. import math
  8. import time
  9. import colorsys
  10. from luma.led_matrix.device import apa102
  11. from luma.core.render import canvas
  12. device = apa102(width=8, height=1)
  13. FALLOFF = 1.9
  14. SCAN_SPEED = 4
  15. def main():
  16. start_time = time.time()
  17. while True:
  18. delta = (time.time() - start_time)
  19. # Offset is a sine wave derived from the time delta
  20. # we use this to animate both the hue and larson scan
  21. # so they are kept in sync with each other
  22. offset = (math.sin(delta * SCAN_SPEED) + 1) / 2
  23. # Use offset to pick the right colour from the hue wheel
  24. hue = int(round(offset * 360))
  25. # Now we generate a value from 0 to 7
  26. offset = int(round(offset * 7))
  27. with canvas(device) as draw:
  28. for x in range(8):
  29. sat = 1.0
  30. val = 7 - (abs(offset - x) * FALLOFF)
  31. val /= 7.0 # Convert to 0.0 to 1.0
  32. val = max(val, 0.0) # Ditch negative values
  33. xhue = hue # Grab hue for this pixel
  34. xhue += (1 - val) * 10 # Use the val offset to give a slight colour trail variation
  35. xhue %= 360 # Clamp to 0-359
  36. xhue /= 360.0 # Convert to 0.0 to 1.0
  37. r, g, b = [int(c * 255) for c in colorsys.hsv_to_rgb(xhue, sat, val)]
  38. draw.point((x, 0), fill=(r, g, b, int(val * 256)))
  39. time.sleep(0.001)
  40. if __name__ == "__main__":
  41. try:
  42. main()
  43. except KeyboardInterrupt:
  44. pass