forked from hybridgroup/gobot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbutton_driver.go
59 lines (50 loc) · 1.06 KB
/
button_driver.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
package gpio
import (
"github.com/hybridgroup/gobot"
)
type ButtonDriver struct {
gobot.Driver
Active bool
}
func NewButtonDriver(a DigitalReader, name string, pin string) *ButtonDriver {
b := &ButtonDriver{
Driver: *gobot.NewDriver(
name,
"ButtonDriver",
a.(gobot.AdaptorInterface),
pin,
),
Active: false,
}
b.AddEvent("push")
b.AddEvent("release")
return b
}
func (b *ButtonDriver) adaptor() DigitalReader {
return b.Adaptor().(DigitalReader)
}
func (b *ButtonDriver) Start() bool {
state := 0
gobot.Every(b.Interval(), func() {
newValue := b.readState()
if newValue != state && newValue != -1 {
state = newValue
b.update(newValue)
}
})
return true
}
func (b *ButtonDriver) Halt() bool { return true }
func (b *ButtonDriver) Init() bool { return true }
func (b *ButtonDriver) readState() int {
return b.adaptor().DigitalRead(b.Pin())
}
func (b *ButtonDriver) update(newVal int) {
if newVal == 1 {
b.Active = true
gobot.Publish(b.Event("push"), newVal)
} else {
b.Active = false
gobot.Publish(b.Event("release"), newVal)
}
}