-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbutton.go
More file actions
94 lines (84 loc) · 2.17 KB
/
button.go
File metadata and controls
94 lines (84 loc) · 2.17 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package main
import (
"time"
)
// Button is a simple pushbutton that registers when the voltage on a GPIO pin changes suddenly.
type Button struct {
pin PiPin
callback func()
bouncetime time.Duration
pushed time.Time
disabled bool
done chan bool
}
// NewGpioButton sets up a specific GPIO pin as a button, and runs the callback when it is pressed.
func NewGpioButton(pin uint8, callback func()) *Button {
return newButton(NewGpio(pin), callback)
}
func newButton(pin PiPin, callback func()) *Button {
b := Button{
pin: pin,
callback: callback,
bouncetime: 150 * time.Millisecond,
pushed: time.Now().Add(-1 * time.Second),
done: make(chan bool),
}
return &b
}
// Start runs a thread in the background that monitors the button activity.
func (b *Button) Start() {
started := make(chan bool)
go b.runLoop(&started)
if <-started { // Wait for loop to start
Debug("Button loop started")
}
}
func (b *Button) runLoop(started *chan bool) {
b.pin.Output(Low)
b.pin.InputEdge(PullUp, RisingEdge)
*started <- true
for {
if b.pin.WaitForEdge(time.Second) {
if b.IsDisabled() {
time.Sleep(time.Second)
continue
}
now := time.Now() // Here for debugging purposes
state := b.pin.Read()
if b.pushed.Add(b.bouncetime).Before(now) {
if state == Low {
b.pushed = now // filter noise of up/down
Debug("Button Pushed: Running Callback")
b.callback()
} else {
Debug("State is High, no callback")
}
} else {
Debug("Bouncetime not encountered")
}
Debug("Edge Detected: %s", state)
}
select {
case <-b.done:
return
default: // Required to not block
}
}
}
// Disable allows you to disable the button, ignoring any pushes that come.
func (b *Button) Disable() {
b.disabled = true
}
// Enable re-enables a button that has been disabled, so it will no longer ignore pushes.
func (b *Button) Enable() {
b.disabled = false
}
// IsDisabled returns true if the button is in a disabled state.
func (b *Button) IsDisabled() bool {
return b.disabled
}
// Stop kills the thread that is monitoring the button activity.
func (b *Button) Stop() {
b.done <- true
Debug("Button stopped")
}