nicebadge/tutorial/basics/step7/main.go

55 lines
1.2 KiB
Go
Raw Normal View History

2026-04-18 11:01:06 +00:00
package main
import (
"image/color"
"machine"
"time"
"tinygo.org/x/drivers/encoders"
"tinygo.org/x/drivers/ws2812"
)
func main() {
// WS2812 LEDs are on pin P1_11
neo := machine.P1_11
neo.Configure(machine.PinConfig{Mode: machine.PinOutput})
leds := ws2812.New(neo)
ledColors := make([]color.RGBA, 2)
// rotary encoder: A=P1_00, B=P0_24; push button=P0_22
enc := encoders.NewQuadratureViaInterrupt(machine.P1_00, machine.P0_24)
enc.Configure(encoders.QuadratureConfig{Precision: 4})
btnRot := machine.P0_22
btnRot.Configure(machine.PinConfig{Mode: machine.PinInputPullup})
var k uint8
for {
// pressing the rotary button resets position to zero
if !btnRot.Get() {
enc.SetPosition(0)
}
// encoder position cycles through the rainbow
k = uint8(enc.Position())
ledColors[0] = getRainbowRGB(k)
ledColors[1] = getRainbowRGB(k + 85)
leds.WriteColors(ledColors)
time.Sleep(20 * time.Millisecond)
}
}
func getRainbowRGB(i uint8) color.RGBA {
if i < 85 {
return color.RGBA{i * 3, 255 - i*3, 0, 255}
} else if i < 170 {
i -= 85
return color.RGBA{255 - i*3, 0, i * 3, 255}
}
i -= 170
return color.RGBA{0, i * 3, 255 - i*3, 255}
}