neopixel_writer.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. """Control NeoPixel-style light strips from ThingFlow.
  2. num_pixels and bytes_per_pixel will vary, depending on your light strip.
  3. Set pinno to the gpio pin number where you connected the data line of
  4. the NeoPixel.
  5. If you have bytes_per_pixel=3, the events will be of the form:
  6. (pixelno, r, g, b)
  7. If you have bytes_per_pixel=4, the events will be of the form:
  8. (pixelno, r, g, b, w)
  9. """
  10. from machine import Pin
  11. from neopixel import NeoPixel
  12. class NeoPixelWriter:
  13. def __init__(self, num_pixels=10, bytes_per_pixel=4, pinno=15):
  14. pin = Pin(pinno, Pin.OUT)
  15. self.np = NeoPixel(pin, num_pixels, bpp=bytes_per_pixel)
  16. self.bytes_per_pixel = bytes_per_pixel
  17. self.tuple_len = bytes_per_pixel+1
  18. def on_next(self, x):
  19. """The event should be a tuple/list where the first element
  20. is the pixel number and the rest are the settings for that pixel
  21. OR it can be a standard (sensor_id, ts, event) tuple, where the control
  22. message is in the third element.
  23. """
  24. if len(x)==3 and (isinstance(x[2], tuple) or isinstance(x[2], list)) and \
  25. len(x[2])==self.tuple_len:
  26. x = x[2] # the control message is embedded in a standard triple
  27. elif len(x)!=self.tuple_len:
  28. raise Exception("expecting a tuple of length %d" % self.tuple_len)
  29. pixel = x[0]
  30. self.np[pixel] = x[1:]
  31. self.np.write()
  32. def on_error(self, e):
  33. pass
  34. def on_completed(self):
  35. pass