hybridgroup.gobot/drivers/gpio/makey_button_driver.go

100 lines
2.3 KiB
Go
Raw Normal View History

2014-04-28 10:34:16 +08:00
package gpio
import (
"time"
"gobot.io/x/gobot"
2014-04-28 10:34:16 +08:00
)
// MakeyButtonDriver Represents a Makey Button
2014-04-28 10:34:16 +08:00
type MakeyButtonDriver struct {
name string
pin string
halt chan bool
2014-11-30 03:02:10 +08:00
connection DigitalReader
Active bool
interval time.Duration
gobot.Eventer
2014-04-28 10:34:16 +08:00
}
// NewMakeyButtonDriver returns a new MakeyButtonDriver with a polling interval of
// 10 Milliseconds given a DigitalReader and pin.
//
2016-07-14 00:44:47 +08:00
// 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: gobot.DefaultName("MakeyButton"),
2014-11-30 03:02:10 +08:00
connection: a,
pin: pin,
Active: false,
Eventer: gobot.NewEventer(),
interval: 10 * time.Millisecond,
halt: make(chan bool),
2014-04-28 10:34:16 +08:00
}
if len(v) > 0 {
m.interval = v[0]
}
2014-11-30 03:02:10 +08:00
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
2014-11-30 03:02:10 +08:00
func (b *MakeyButtonDriver) Connection() gobot.Connection { return b.connection.(gobot.Connection) }
2014-04-28 10:34:16 +08:00
// Start starts the MakeyButtonDriver and polls the state of the button at the given interval.
2014-09-28 02:34:13 +08:00
//
// Emits the Events:
// Push int - On button push
// Release int - On button release
// Error error - On button error
func (b *MakeyButtonDriver) Start() (err error) {
2014-12-17 05:42:48 +08:00
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
}
2014-04-28 10:34:16 +08:00
}
}()
return
2014-04-28 10:34:16 +08:00
}
2014-09-28 02:34:13 +08:00
// Halt stops polling the makey button for new information
func (b *MakeyButtonDriver) Halt() (err error) {
b.halt <- true
return
}