tinygo.org/x/drivers@v0.27.1-0.20240509133757-7dbca2a54349/examples/apa102/itsybitsy-m0/main.go (about) 1 // This example demostrates how to control the "Dotstar" (APA102) LED included 2 // on the Adafruit Itsy Bitsy M0 board. It implements a "rainbow effect" based 3 // on the following example: 4 // https://github.com/adafruit/Adafruit_Learning_System_Guides/blob/master/CircuitPython_Essentials/CircuitPython_Internal_RGB_LED_rainbow.py 5 package main 6 7 import ( 8 "image/color" 9 "machine" 10 "time" 11 12 "tinygo.org/x/drivers/apa102" 13 ) 14 15 var ( 16 apa *apa102.Device 17 18 pwm = machine.TCC0 19 leds = make([]color.RGBA, 1) 20 wheel = &Wheel{Brightness: 0x10} 21 ) 22 23 func init() { 24 25 // APA102 on Itsy Bitsy is connected to pins that require a software-based 26 // SPI implementation. 27 apa = apa102.NewSoftwareSPI(machine.PA00, machine.PA01, 1) 28 29 // Configure the regular on-board LED for PWM fading 30 err := pwm.Configure(machine.PWMConfig{}) 31 if err != nil { 32 println("failed to configure PWM") 33 return 34 } 35 } 36 37 func main() { 38 channelLED, err := pwm.Channel(machine.LED) 39 if err != nil { 40 println("failed to configure LED PWM channel") 41 return 42 } 43 44 // We'll fade the on-board LED in a goroutine to show/ensure that the APA102 45 // works fine with the scheduler enabled. Comment this out to test this code 46 // with the scheduler disabled. 47 go func() { 48 for i, brightening := uint8(0), false; ; i++ { 49 if i == 0 { 50 brightening = !brightening 51 continue 52 } 53 var brightness uint32 = uint32(i) 54 if !brightening { 55 brightness = 256 - brightness 56 } 57 pwm.Set(channelLED, pwm.Top()*brightness/256) 58 time.Sleep(5 * time.Millisecond) 59 } 60 }() 61 62 // Use the "wheel" function from Adafruit's example to cycle the APA102 63 for { 64 leds[0] = wheel.Next() 65 apa.WriteColors(leds) 66 time.Sleep(25 * time.Millisecond) 67 } 68 69 } 70 71 // Wheel is a port of Adafruit's Circuit Python example referenced above. 72 type Wheel struct { 73 Brightness uint8 74 pos uint8 75 } 76 77 // Next increments the internal state of the color and returns the new RGBA 78 func (w *Wheel) Next() (c color.RGBA) { 79 pos := w.pos 80 if w.pos < 85 { 81 c = color.RGBA{R: 0xFF - pos*3, G: pos * 3, B: 0x0, A: w.Brightness} 82 } else if w.pos < 170 { 83 pos -= 85 84 c = color.RGBA{R: 0x0, G: 0xFF - pos*3, B: pos * 3, A: w.Brightness} 85 } else { 86 pos -= 170 87 c = color.RGBA{R: pos * 3, G: 0x0, B: 0xFF - pos*3, A: w.Brightness} 88 } 89 w.pos++ 90 return 91 }