/
button.go
55 lines (47 loc) · 928 Bytes
/
button.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
package main
import (
"github.com/mrmorphic/hwio"
)
type ButtonCallback func()
type ButtonChangeCallback func(state int)
type Button struct {
pin hwio.Pin
Rising ButtonCallback
Falling ButtonCallback
Change ButtonChangeCallback
}
func NewButton(pin string) (*Button, error) {
buttonPin, err := hwio.GetPin(pin)
if err != nil {
return nil, err
}
err = hwio.PinMode(buttonPin, hwio.INPUT)
if err != nil {
return nil, err
}
return &Button{pin: buttonPin}, nil
}
func (b *Button) Poll() {
go func() {
lastState, _ := hwio.DigitalRead(b.pin)
for {
currentState, _ := hwio.DigitalRead(b.pin)
if currentState != lastState {
lastState = currentState
if currentState == 1 {
if b.Rising != nil {
b.Rising()
}
} else {
if b.Falling != nil {
b.Falling()
}
}
if b.Change != nil {
b.Change(currentState)
}
}
hwio.Delay(50)
}
}()
}