|
| 1 | +package ws2812 |
| 2 | + |
| 3 | +import "image/color" |
| 4 | + |
| 5 | +// Strip controls a strip of WS2812B LEDs with a pixel buffer and brightness control. |
| 6 | +// Use NewStrip to create a new instance. |
| 7 | +type Strip struct { |
| 8 | + pixels []color.RGBA |
| 9 | + brightness uint8 |
| 10 | + writeFunc func(pixels []color.RGBA, brightness uint8) error |
| 11 | +} |
| 12 | + |
| 13 | +// SetPixel sets the color of pixel at index i. |
| 14 | +func (s *Strip) SetPixel(i int, c color.RGBA) { |
| 15 | + if i >= 0 && i < len(s.pixels) { |
| 16 | + s.pixels[i] = c |
| 17 | + } |
| 18 | +} |
| 19 | + |
| 20 | +// Show sends the current pixel buffer to the LED strip. |
| 21 | +func (s *Strip) Show() error { |
| 22 | + return s.writeFunc(s.pixels, s.brightness) |
| 23 | +} |
| 24 | + |
| 25 | +// SetBrightness sets the global brightness (0-255). |
| 26 | +func (s *Strip) SetBrightness(b uint8) { |
| 27 | + s.brightness = b |
| 28 | +} |
| 29 | + |
| 30 | +// Fill sets all pixels to the given color. |
| 31 | +func (s *Strip) Fill(c color.RGBA) { |
| 32 | + for i := range s.pixels { |
| 33 | + s.pixels[i] = c |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +// Clear turns off all pixels. |
| 38 | +func (s *Strip) Clear() { |
| 39 | + s.Fill(color.RGBA{}) |
| 40 | +} |
| 41 | + |
| 42 | +// NumPixels returns the number of pixels in the strip. |
| 43 | +func (s *Strip) NumPixels() int { |
| 44 | + return len(s.pixels) |
| 45 | +} |
| 46 | + |
| 47 | +// applyBrightness scales a color by the brightness value. |
| 48 | +func applyBrightness(c color.RGBA, brightness uint8) (r, g, b uint8) { |
| 49 | + r = uint8((uint16(c.R) * uint16(brightness)) >> 8) |
| 50 | + g = uint8((uint16(c.G) * uint16(brightness)) >> 8) |
| 51 | + b = uint8((uint16(c.B) * uint16(brightness)) >> 8) |
| 52 | + return |
| 53 | +} |
0 commit comments