leds.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import time
  2. from machine import PWM, Pin
  3. from config import LED_LIST
  4. class Leds:
  5. def __init__(self):
  6. self.led_count = len(LED_LIST)
  7. self.pwm = [None] * self.led_count
  8. self.vals = [x[3] for x in LED_LIST]
  9. self.diff = [0] * self.led_count
  10. self.stepId = [0] * self.led_count
  11. self.steps = 50
  12. self.frequency = 800
  13. self.enabled = True
  14. def init(self, i):
  15. if not self.pwm[i]:
  16. self.pwm[i] = PWM(Pin(LED_LIST[i][1]), channel=LED_LIST[i][2], freq=self.frequency, duty=0)
  17. def deinit(self, i):
  18. if self.pwm[i]:
  19. self.pwm[i].deinit()
  20. self.pwm[i] = None
  21. def enable(self):
  22. self.enabled = True
  23. for i in range(self.led_count):
  24. self.diff[i] = float(self.vals[i]) / self.steps
  25. self.stepId[i] = 0
  26. def disable(self):
  27. for i in range(self.led_count):
  28. self.setColor(i, 0)
  29. self.enabled = False
  30. def setSteps(self, n):
  31. if n < 1:
  32. n = 1
  33. self.steps = n
  34. def setColor(self, i, val):
  35. if val < 0:
  36. val = 0
  37. elif val > 256:
  38. val = 256
  39. self.vals[i] = val
  40. if not self.enabled:
  41. return
  42. if not self.pwm[i]:
  43. self.diff[i] = self.vals[i]
  44. else:
  45. self.diff[i] = self.vals[i] - (self.pwm[i].duty() + 1)
  46. self.stepId[i] = 0
  47. def update(self):
  48. for i in range(self.led_count):
  49. if self.enabled and not self.pwm[i] and self.vals[i]:
  50. self.init(i)
  51. elif not self.pwm[i]:
  52. continue
  53. if self.stepId[i] > self.steps:
  54. self.diff[i] = 0
  55. if self.vals[i] == 0 or not self.enabled:
  56. self.deinit(i)
  57. else:
  58. if self.enabled:
  59. val = int(self.vals[i] - self.diff[i] * float(self.steps - self.stepId[i]) / self.steps) - 1
  60. else:
  61. val = int(-self.diff[i] * float(self.steps - self.stepId[i]) / self.steps)
  62. if val < 0:
  63. val = 0
  64. if val > 255:
  65. val = 255
  66. self.pwm[i].duty(val)
  67. self.stepId[i] += 1