gobot.io/x/gobot/v2@v2.1.0/drivers/spi/apa102.go (about) 1 package spi 2 3 import ( 4 "image/color" 5 "math" 6 ) 7 8 // APA102Driver is a driver for the APA102 programmable RGB LEDs. 9 type APA102Driver struct { 10 *Driver 11 vals []color.RGBA 12 brightness uint8 13 } 14 15 // NewAPA102Driver creates a new Gobot Driver for APA102 RGB LEDs. 16 // 17 // Params: 18 // a *Adaptor - the Adaptor to use with this Driver. 19 // count int - how many LEDs are in the array controlled by this driver. 20 // bright - the default brightness to apply for all LEDs (must be between 0 and 31). 21 // 22 // Optional params: 23 // spi.WithBusNumber(int): bus to use with this driver. 24 // spi.WithChipNumber(int): chip to use with this driver. 25 // spi.WithMode(int): mode to use with this driver. 26 // spi.WithBitCount(int): number of bits to use with this driver. 27 // spi.WithSpeed(int64): speed in Hz to use with this driver. 28 // 29 func NewAPA102Driver(a Connector, count int, bright uint8, options ...func(Config)) *APA102Driver { 30 d := &APA102Driver{ 31 Driver: NewDriver(a, "APA102"), 32 vals: make([]color.RGBA, count), 33 brightness: uint8(math.Min(float64(bright), 31)), 34 } 35 for _, option := range options { 36 option(d) 37 } 38 return d 39 } 40 41 // SetRGBA sets the ith LED's color to the given RGBA value. 42 // A subsequent call to Draw is required to transmit values 43 // to the LED strip. 44 func (d *APA102Driver) SetRGBA(i int, v color.RGBA) { 45 d.vals[i] = v 46 } 47 48 // SetBrightness sets the ith LED's brightness to the given value. 49 // Must be between 0 and 31. 50 func (d *APA102Driver) SetBrightness(i uint8) { 51 d.brightness = uint8(math.Min(float64(i), 31)) 52 } 53 54 // Brightness return driver brightness value. 55 func (d *APA102Driver) Brightness() uint8 { 56 return d.brightness 57 } 58 59 // Draw displays the RGBA values set on the actual LED strip. 60 func (d *APA102Driver) Draw() error { 61 // TODO(jbd): dotstar allows other RGBA alignments, support those layouts. 62 n := len(d.vals) 63 64 tx := make([]byte, 4*(n+1)+(n/2+1)) 65 tx[0] = 0x00 66 tx[1] = 0x00 67 tx[2] = 0x00 68 tx[3] = 0x00 69 70 for i, c := range d.vals { 71 j := (i + 1) * 4 72 if c.A != 0 { 73 tx[j] = 0xe0 + byte(math.Min(float64(c.A), 31)) 74 } else { 75 tx[j] = 0xe0 + byte(d.brightness) 76 } 77 tx[j+1] = c.B 78 tx[j+2] = c.G 79 tx[j+3] = c.R 80 } 81 82 // end frame with at least n/2 0xff vals 83 for i := (n + 1) * 4; i < len(tx); i++ { 84 tx[i] = 0xff 85 } 86 87 return d.connection.WriteBytes(tx) 88 }