Repository navigation
Expand file tree
/
Copy pathbuttons.go
More file actions
79 lines (66 loc) · 1.29 KB
/
Copy pathbuttons.go
File metadata and controls
79 lines (66 loc) · 1.29 KB
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
package main
import (
"fmt"
"os"
"runtime"
"sync/atomic"
"time"
rpio "github.com/stianeikeland/go-rpio"
)
type RPButtonEvent struct {
Pin int
When time.Time
}
type RPButtonMonitor struct {
Events chan RPButtonEvent
exit int32
pins []rpio.Pin
}
func NewRPButtonMonitor(pinids ...int) *RPButtonMonitor {
mon := &RPButtonMonitor{
Events: make(chan RPButtonEvent, 16),
}
if runtime.GOOS == "darwin" { // debugging mode
return mon
}
if err := rpio.Open(); err != nil {
fmt.Println(err)
os.Exit(1)
}
for _, id := range pinids {
pin := rpio.Pin(id)
pin.Input()
pin.PullOff()
mon.pins = append(mon.pins, pin)
}
go mon.detectEdges()
return mon
}
func (mon *RPButtonMonitor) Shutdown() {
atomic.StoreInt32(&mon.exit, 1)
for atomic.LoadInt32(&mon.exit) != 2 {
time.Sleep(50 * time.Millisecond)
}
rpio.Close()
}
func (mon *RPButtonMonitor) detectEdges() {
for atomic.LoadInt32(&mon.exit) == 0 {
for _, pin := range mon.pins {
if pin.Read() == rpio.Low {
mon.Events <- RPButtonEvent{
Pin: int(pin),
When: time.Now(),
}
// wait until button is released
for {
if pin.Read() == rpio.High {
break
}
time.Sleep(50 * time.Millisecond)
}
}
}
time.Sleep(50 * time.Millisecond)
}
atomic.StoreInt32(&mon.exit, 2)
}