-
-
Notifications
You must be signed in to change notification settings - Fork 15
/
kbgpio.go
133 lines (114 loc) · 2.34 KB
/
kbgpio.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
//go:build tinygo
package keyboard
import (
"machine"
)
type GpioKeyboard struct {
State []State
Keys [][]Keycode
options Options
callback Callback
Col []machine.Pin
cycleCounter []uint8
debounce uint8
}
func (d *Device) AddGpioKeyboard(pins []machine.Pin, keys [][]Keycode, opt ...Option) *GpioKeyboard {
col := len(pins)
state := make([]State, col)
cycleCnt := make([]uint8, len(state))
o := Options{
InvertButtonState: true,
}
for _, f := range opt {
f(&o)
}
keydef := make([][]Keycode, LayerCount)
for l := 0; l < len(keydef); l++ {
keydef[l] = make([]Keycode, len(state))
}
for l := 0; l < len(keys); l++ {
for kc := 0; kc < len(keys[l]); kc++ {
keydef[l][kc] = keys[l][kc]
}
}
k := &GpioKeyboard{
Col: pins,
State: state,
Keys: keydef,
options: o,
callback: func(layer, index int, state State) {},
cycleCounter: cycleCnt,
debounce: 8,
}
d.kb = append(d.kb, k)
return k
}
func (d *GpioKeyboard) SetCallback(fn Callback) {
d.callback = fn
}
func (d *GpioKeyboard) Callback(layer, index int, state State) {
if d.callback != nil {
d.callback(layer, index, state)
}
}
func (d *GpioKeyboard) Get() []State {
for c := range d.Col {
current := d.Col[c].Get()
if d.options.InvertButtonState {
current = !current
}
switch d.State[c] {
case None:
if current {
if d.cycleCounter[c] >= d.debounce {
d.State[c] = NoneToPress
d.cycleCounter[c] = 0
} else {
d.cycleCounter[c]++
}
} else {
d.cycleCounter[c] = 0
}
case NoneToPress:
d.State[c] = Press
case Press:
if current {
d.cycleCounter[c] = 0
} else {
if d.cycleCounter[c] >= d.debounce {
d.State[c] = PressToRelease
d.cycleCounter[c] = 0
} else {
d.cycleCounter[c]++
}
}
case PressToRelease:
d.State[c] = None
}
}
return d.State
}
func (d *GpioKeyboard) Key(layer, index int) Keycode {
if layer >= LayerCount {
return 0
}
if index >= len(d.Keys[layer]) {
return 0
}
return d.Keys[layer][index]
}
func (d *GpioKeyboard) SetKeycode(layer, index int, key Keycode) {
if layer >= LayerCount {
return
}
if index >= len(d.Keys[layer]) {
return
}
d.Keys[layer][index] = key
}
func (d *GpioKeyboard) GetKeyCount() int {
return len(d.State)
}
func (d *GpioKeyboard) Init() error {
return nil
}