@@ -18,7 +18,8 @@ var errUnknownClockSpeed = errors.New("ws2812: unknown CPU clock speed")
1818// Device wraps a pin object for an easy driver interface.
1919type Device struct {
2020 Pin machine.Pin
21- writeColorFunc func (Device , []color.RGBA ) error
21+ brightness uint8
22+ writeColorFunc func (Device , []color.RGBA , uint8 ) error
2223}
2324
2425// deprecated, use NewWS2812 or NewSK6812 depending on which device you want.
@@ -40,10 +41,16 @@ func NewWS2812(pin machine.Pin) Device {
4041func NewSK6812 (pin machine.Pin ) Device {
4142 return Device {
4243 Pin : pin ,
44+ brightness : 255 ,
4345 writeColorFunc : writeColorsRGBA ,
4446 }
4547}
4648
49+ // SetBrightness sets the global brightness (0-255).
50+ func (d * Device ) SetBrightness (b uint8 ) {
51+ d .brightness = b
52+ }
53+
4754// Write the raw bitstring out using the WS2812 protocol.
4855func (d Device ) Write (buf []byte ) (n int , err error ) {
4956 for _ , c := range buf {
@@ -55,24 +62,35 @@ func (d Device) Write(buf []byte) (n int, err error) {
5562// Write the given color slice out using the WS2812 protocol.
5663// Colors are sent out in the usual GRB(A) format.
5764func (d Device ) WriteColors (buf []color.RGBA ) (err error ) {
58- return d .writeColorFunc (d , buf )
65+ return d .writeColorFunc (d , buf , d . brightness )
5966}
6067
61- func writeColorsRGB (d Device , buf []color.RGBA ) (err error ) {
68+ func writeColorsRGB (d Device , buf []color.RGBA , brightness uint8 ) (err error ) {
6269 for _ , color := range buf {
63- d .WriteByte (color .G ) // green
64- d .WriteByte (color .R ) // red
65- err = d .WriteByte (color .B ) // blue
70+ r , g , b := applyBrightness (color , brightness )
71+ d .WriteByte (g ) // green
72+ d .WriteByte (r ) // red
73+ err = d .WriteByte (b ) // blue
6674 }
6775 return
6876}
6977
70- func writeColorsRGBA (d Device , buf []color.RGBA ) (err error ) {
78+ func writeColorsRGBA (d Device , buf []color.RGBA , brightness uint8 ) (err error ) {
7179 for _ , color := range buf {
72- d .WriteByte (color .G ) // green
73- d .WriteByte (color .R ) // red
74- d .WriteByte (color .B ) // blue
80+ r , g , b := applyBrightness (color , brightness )
81+
82+ d .WriteByte (g ) // green
83+ d .WriteByte (r ) // red
84+ d .WriteByte (b ) // blue
7585 err = d .WriteByte (color .A ) // alpha
7686 }
7787 return
7888}
89+
90+ // applyBrightness scales a color by the brightness value.
91+ func applyBrightness (c color.RGBA , brightness uint8 ) (r , g , b uint8 ) {
92+ r = uint8 ((uint16 (c .R ) * uint16 (brightness )) >> 8 )
93+ g = uint8 ((uint16 (c .G ) * uint16 (brightness )) >> 8 )
94+ b = uint8 ((uint16 (c .B ) * uint16 (brightness )) >> 8 )
95+ return
96+ }
0 commit comments