forked from hybridgroup/gobot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
makey_button_driver.go
99 lines (86 loc) · 2.31 KB
/
makey_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
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
package gpio
import (
"time"
"gobot.io/x/gobot"
)
// MakeyButtonDriver Represents a Makey Button
type MakeyButtonDriver struct {
name string
pin string
halt chan bool
connection DigitalReader
Active bool
interval time.Duration
gobot.Eventer
}
// NewMakeyButtonDriver returns a new MakeyButtonDriver with a polling interval of
// 10 Milliseconds given a DigitalReader and pin.
//
// Optionally accepts:
// time.Duration: Interval at which the ButtonDriver is polled for new information
func NewMakeyButtonDriver(a DigitalReader, pin string, v ...time.Duration) *MakeyButtonDriver {
m := &MakeyButtonDriver{
name: "MakeyButton",
connection: a,
pin: pin,
Active: false,
Eventer: gobot.NewEventer(),
interval: 10 * time.Millisecond,
halt: make(chan bool),
}
if len(v) > 0 {
m.interval = v[0]
}
m.AddEvent(Error)
m.AddEvent(ButtonPush)
m.AddEvent(ButtonRelease)
return m
}
// Name returns the MakeyButtonDrivers name
func (b *MakeyButtonDriver) Name() string { return b.name }
// SetName sets the MakeyButtonDrivers name
func (b *MakeyButtonDriver) SetName(n string) { b.name = n }
// Pin returns the MakeyButtonDrivers pin
func (b *MakeyButtonDriver) Pin() string { return b.pin }
// Connection returns the MakeyButtonDrivers Connection
func (b *MakeyButtonDriver) Connection() gobot.Connection { return b.connection.(gobot.Connection) }
// Start starts the MakeyButtonDriver and polls the state of the button at the given interval.
//
// Emits the Events:
// Push int - On button push
// Release int - On button release
// Error error - On button error
func (b *MakeyButtonDriver) Start() (err error) {
state := 1
go func() {
timer := time.NewTimer(b.interval)
timer.Stop()
for {
newValue, err := b.connection.DigitalRead(b.Pin())
if err != nil {
b.Publish(Error, err)
} else if newValue != state && newValue != -1 {
state = newValue
if newValue == 0 {
b.Active = true
b.Publish(ButtonPush, newValue)
} else {
b.Active = false
b.Publish(ButtonRelease, newValue)
}
}
timer.Reset(b.interval)
select {
case <-timer.C:
case <-b.halt:
return
}
}
}()
return
}
// Halt stops polling the makey button for new information
func (b *MakeyButtonDriver) Halt() (err error) {
b.halt <- true
return
}