You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

227 lines
7.7 KiB

  1. # The MIT License (MIT)
  2. #
  3. # Copyright (c) 2016 Damien P. George
  4. # Copyright (c) 2017 Scott Shawcroft for Adafruit Industries
  5. #
  6. # Permission is hereby granted, free of charge, to any person obtaining a copy
  7. # of this software and associated documentation files (the "Software"), to deal
  8. # in the Software without restriction, including without limitation the rights
  9. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. # copies of the Software, and to permit persons to whom the Software is
  11. # furnished to do so, subject to the following conditions:
  12. #
  13. # The above copyright notice and this permission notice shall be included in
  14. # all copies or substantial portions of the Software.
  15. #
  16. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. # THE SOFTWARE.
  23. """
  24. `neopixel` - NeoPixel strip driver
  25. ====================================================
  26. * Author(s): Damien P. George & Scott Shawcroft
  27. """
  28. import math
  29. import digitalio
  30. from neopixel_write import neopixel_write
  31. __version__ = "3.3.0"
  32. __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_NeoPixel.git"
  33. # Pixel color order constants
  34. RGB = (0, 1, 2)
  35. """Red Green Blue"""
  36. GRB = (1, 0, 2)
  37. """Green Red Blue"""
  38. RGBW = (0, 1, 2, 3)
  39. """Red Green Blue White"""
  40. GRBW = (1, 0, 2, 3)
  41. """Green Red Blue White"""
  42. class NeoPixel:
  43. """
  44. A sequence of neopixels.
  45. :param ~microcontroller.Pin pin: The pin to output neopixel data on.
  46. :param int n: The number of neopixels in the chain
  47. :param int bpp: Bytes per pixel. 3 for RGB and 4 for RGBW pixels.
  48. :param float brightness: Brightness of the pixels between 0.0 and 1.0 where 1.0 is full
  49. brightness
  50. :param bool auto_write: True if the neopixels should immediately change when set. If False,
  51. `show` must be called explicitly.
  52. :param tuple pixel_order: Set the pixel color channel order. GRBW is set by default.
  53. Example for Circuit Playground Express:
  54. .. code-block:: python
  55. import neopixel
  56. from board import *
  57. RED = 0x100000 # (0x10, 0, 0) also works
  58. pixels = neopixel.NeoPixel(NEOPIXEL, 10)
  59. for i in range(len(pixels)):
  60. pixels[i] = RED
  61. Example for Circuit Playground Express setting every other pixel red using a slice:
  62. .. code-block:: python
  63. import neopixel
  64. from board import *
  65. import time
  66. RED = 0x100000 # (0x10, 0, 0) also works
  67. # Using ``with`` ensures pixels are cleared after we're done.
  68. with neopixel.NeoPixel(NEOPIXEL, 10) as pixels:
  69. pixels[::2] = [RED] * (len(pixels) // 2)
  70. time.sleep(2)
  71. """
  72. def __init__(self, pin, n, *, bpp=3, brightness=1.0, auto_write=True, pixel_order=None):
  73. self.pin = digitalio.DigitalInOut(pin)
  74. self.pin.direction = digitalio.Direction.OUTPUT
  75. self.n = n
  76. if pixel_order is None:
  77. self.order = GRBW
  78. self.bpp = bpp
  79. else:
  80. self.order = pixel_order
  81. self.bpp = len(self.order)
  82. self.buf = bytearray(self.n * self.bpp)
  83. # Set auto_write to False temporarily so brightness setter does _not_
  84. # call show() while in __init__.
  85. self.auto_write = False
  86. self.brightness = brightness
  87. self.auto_write = auto_write
  88. def deinit(self):
  89. """Blank out the NeoPixels and release the pin."""
  90. for i in range(len(self.buf)):
  91. self.buf[i] = 0
  92. neopixel_write(self.pin, self.buf)
  93. self.pin.deinit()
  94. def __enter__(self):
  95. return self
  96. def __exit__(self, exception_type, exception_value, traceback):
  97. self.deinit()
  98. def __repr__(self):
  99. return "[" + ", ".join([str(x) for x in self]) + "]"
  100. def _set_item(self, index, value):
  101. if index < 0:
  102. index += len(self)
  103. if index >= self.n or index < 0:
  104. raise IndexError
  105. offset = index * self.bpp
  106. r = 0
  107. g = 0
  108. b = 0
  109. w = 0
  110. if isinstance(value, int):
  111. r = value >> 16
  112. g = (value >> 8) & 0xff
  113. b = value & 0xff
  114. w = 0
  115. # If all components are the same and we have a white pixel then use it
  116. # instead of the individual components.
  117. if self.bpp == 4 and r == g and g == b:
  118. w = r
  119. r = 0
  120. g = 0
  121. b = 0
  122. elif len(value) == self.bpp:
  123. if self.bpp == 3:
  124. r, g, b = value
  125. else:
  126. r, g, b, w = value
  127. self.buf[offset + self.order[0]] = r
  128. self.buf[offset + self.order[1]] = g
  129. self.buf[offset + self.order[2]] = b
  130. if self.bpp == 4:
  131. self.buf[offset + self.order[3]] = w
  132. def __setitem__(self, index, val):
  133. if isinstance(index, slice):
  134. start, stop, step = index.indices(len(self.buf) // self.bpp)
  135. length = stop - start
  136. if step != 0:
  137. length = math.ceil(length / step)
  138. if len(val) != length:
  139. raise ValueError("Slice and input sequence size do not match.")
  140. for val_i, in_i in enumerate(range(start, stop, step)):
  141. self._set_item(in_i, val[val_i])
  142. else:
  143. self._set_item(index, val)
  144. if self.auto_write:
  145. self.show()
  146. def __getitem__(self, index):
  147. if isinstance(index, slice):
  148. out = []
  149. for in_i in range(*index.indices(len(self.buf) // self.bpp)):
  150. out.append(tuple(self.buf[in_i * self.bpp + self.order[i]]
  151. for i in range(self.bpp)))
  152. return out
  153. if index < 0:
  154. index += len(self)
  155. if index >= self.n or index < 0:
  156. raise IndexError
  157. offset = index * self.bpp
  158. return tuple(self.buf[offset + self.order[i]]
  159. for i in range(self.bpp))
  160. def __len__(self):
  161. return len(self.buf) // self.bpp
  162. @property
  163. def brightness(self):
  164. """Overall brightness of the pixel"""
  165. return self._brightness
  166. @brightness.setter
  167. def brightness(self, brightness):
  168. # pylint: disable=attribute-defined-outside-init
  169. self._brightness = min(max(brightness, 0.0), 1.0)
  170. if self.auto_write:
  171. self.show()
  172. def fill(self, color):
  173. """Colors all pixels the given ***color***."""
  174. auto_write = self.auto_write
  175. self.auto_write = False
  176. for i, _ in enumerate(self):
  177. self[i] = color
  178. if auto_write:
  179. self.show()
  180. self.auto_write = auto_write
  181. def write(self):
  182. """.. deprecated: 1.0.0
  183. Use ``show`` instead. It matches Micro:Bit and Arduino APIs."""
  184. self.show()
  185. def show(self):
  186. """Shows the new colors on the pixels themselves if they haven't already
  187. been autowritten.
  188. The colors may or may not be showing after this function returns because
  189. it may be done asynchronously."""
  190. if self.brightness > 0.99:
  191. neopixel_write(self.pin, self.buf)
  192. else:
  193. neopixel_write(self.pin, bytearray([int(i * self.brightness) for i in self.buf]))