concertina

Elecronic concertina
git clone https://git.woozle.org/neale/concertina.git

concertina / pkg / led
Neale Pickett  ·  2026-02-12

pin.go

 1//go:build arduino
 2
 3package led
 4
 5import "machine"
 6
 7// BUG: machine should make this an exported interface, or export timerType
 8type PWM interface {
 9	Configure(config machine.PWMConfig) error
10	Channel(pin machine.Pin) (channel uint8, err error)
11	Set(chanel uint8, value uint32)
12	Top() uint32
13}
14
15type Pin struct {
16	machine.Pin
17	pwm PWM
18	invert bool		// Does a low pin turn the LED on?
19}
20
21func (p Pin) Enable() {
22	if p.pwm != nil {
23		pwm.Configure(machine.PWMConfig{})
24		pwm.Channel(p.Pin)
25		return
26	}
27	p.Configure(machine.PinConfig{machine.PinOutput})
28}
29
30func (p Pin) Disable() {
31	// XXX: is there a standard way to detach the pwm?
32}
33
34func (p Pin) SetColor(c color.Color) {
35	// Our LED can only make one color. Convert c to gray so we can calculate intensity.
36	g := color.RGBAModel.Convert(c).(color.Gray16)
37	if p.pwm == nil {
38		state := g.Y > 0 // Power the LED for anything other than black
39		if (p.invert) {
40			state = !state
41		}
42		p.Pin.Set(state)
43		return
44	}		
45
46	// Top() is the maximum value you can pass in to set.
47	// cycle is therefore a fraction of top.
48	// BUG: https://tinygo.org/docs/tutorials/pwm/ could make this more clear.
49	// XXX: Is this arithmetic going to overflow uint32?
50	cycle := pwm.Top() * g.Y / 0xffff
51	if p.invert {
52		cycle = pwm.Top() - cycle
53	}
54	pwm.Set(cycle)
55}