tinygo.org/x/drivers@v0.27.1-0.20240509133757-7dbca2a54349/ws2812/ws2812.go (about)

     1  // Package ws2812 implements a driver for WS2812 and SK6812 RGB LED strips.
     2  package ws2812 // import "tinygo.org/x/drivers/ws2812"
     3  
     4  //go:generate go run gen-ws2812.go -arch=cortexm 16 48 64 120 125 168
     5  //go:generate go run gen-ws2812.go -arch=tinygoriscv 160 320
     6  
     7  import (
     8  	"errors"
     9  	"image/color"
    10  	"machine"
    11  )
    12  
    13  var errUnknownClockSpeed = errors.New("ws2812: unknown CPU clock speed")
    14  
    15  // Device wraps a pin object for an easy driver interface.
    16  type Device struct {
    17  	Pin            machine.Pin
    18  	writeColorFunc func(Device, []color.RGBA) error
    19  }
    20  
    21  // deprecated, use NewWS2812 or NewSK6812 depending on which device you want.
    22  // calls NewWS2812() to avoid breaking everyone's existing code.
    23  func New(pin machine.Pin) Device {
    24  	return NewWS2812(pin)
    25  }
    26  
    27  // New returns a new WS2812(RGB) driver.
    28  // It does not touch the pin object: you have
    29  // to configure it as an output pin before calling New.
    30  func NewWS2812(pin machine.Pin) Device {
    31  	return Device{
    32  		Pin:            pin,
    33  		writeColorFunc: writeColorsRGB,
    34  	}
    35  }
    36  
    37  // New returns a new SK6812(RGBA) driver.
    38  // It does not touch the pin object: you have
    39  // to configure it as an output pin before calling New.
    40  func NewSK6812(pin machine.Pin) Device {
    41  	return Device{
    42  		Pin:            pin,
    43  		writeColorFunc: writeColorsRGBA,
    44  	}
    45  }
    46  
    47  // Write the raw bitstring out using the WS2812 protocol.
    48  func (d Device) Write(buf []byte) (n int, err error) {
    49  	for _, c := range buf {
    50  		d.WriteByte(c)
    51  	}
    52  	return len(buf), nil
    53  }
    54  
    55  // Write the given color slice out using the WS2812 protocol.
    56  // Colors are sent out in the usual GRB(A) format.
    57  func (d Device) WriteColors(buf []color.RGBA) (err error) {
    58  	return d.writeColorFunc(d, buf)
    59  }
    60  
    61  func writeColorsRGB(d Device, buf []color.RGBA) (err error) {
    62  	for _, color := range buf {
    63  		d.WriteByte(color.G)       // green
    64  		d.WriteByte(color.R)       // red
    65  		err = d.WriteByte(color.B) // blue
    66  	}
    67  	return
    68  }
    69  
    70  func writeColorsRGBA(d Device, buf []color.RGBA) (err error) {
    71  	for _, color := range buf {
    72  		d.WriteByte(color.G)       // green
    73  		d.WriteByte(color.R)       // red
    74  		d.WriteByte(color.B)       // blue
    75  		err = d.WriteByte(color.A) // alpha
    76  	}
    77  	return
    78  }