gobot.io/x/gobot@v1.16.0/drivers/gpio/button_driver.go (about) 1 package gpio 2 3 import ( 4 "time" 5 6 "gobot.io/x/gobot" 7 ) 8 9 // ButtonDriver Represents a digital Button 10 type ButtonDriver struct { 11 Active bool 12 DefaultState int 13 pin string 14 name string 15 halt chan bool 16 interval time.Duration 17 connection DigitalReader 18 gobot.Eventer 19 } 20 21 // NewButtonDriver returns a new ButtonDriver with a polling interval of 22 // 10 Milliseconds given a DigitalReader and pin. 23 // 24 // Optionally accepts: 25 // time.Duration: Interval at which the ButtonDriver is polled for new information 26 func NewButtonDriver(a DigitalReader, pin string, v ...time.Duration) *ButtonDriver { 27 b := &ButtonDriver{ 28 name: gobot.DefaultName("Button"), 29 connection: a, 30 pin: pin, 31 Active: false, 32 DefaultState: 0, 33 Eventer: gobot.NewEventer(), 34 interval: 10 * time.Millisecond, 35 halt: make(chan bool), 36 } 37 38 if len(v) > 0 { 39 b.interval = v[0] 40 } 41 42 b.AddEvent(ButtonPush) 43 b.AddEvent(ButtonRelease) 44 b.AddEvent(Error) 45 46 return b 47 } 48 49 // Start starts the ButtonDriver and polls the state of the button at the given interval. 50 // 51 // Emits the Events: 52 // Push int - On button push 53 // Release int - On button release 54 // Error error - On button error 55 func (b *ButtonDriver) Start() (err error) { 56 state := b.DefaultState 57 go func() { 58 for { 59 newValue, err := b.connection.DigitalRead(b.Pin()) 60 if err != nil { 61 b.Publish(Error, err) 62 } else if newValue != state && newValue != -1 { 63 state = newValue 64 b.update(newValue) 65 } 66 select { 67 case <-time.After(b.interval): 68 case <-b.halt: 69 return 70 } 71 } 72 }() 73 return 74 } 75 76 // Halt stops polling the button for new information 77 func (b *ButtonDriver) Halt() (err error) { 78 b.halt <- true 79 return 80 } 81 82 // Name returns the ButtonDrivers name 83 func (b *ButtonDriver) Name() string { return b.name } 84 85 // SetName sets the ButtonDrivers name 86 func (b *ButtonDriver) SetName(n string) { b.name = n } 87 88 // Pin returns the ButtonDrivers pin 89 func (b *ButtonDriver) Pin() string { return b.pin } 90 91 // Connection returns the ButtonDrivers Connection 92 func (b *ButtonDriver) Connection() gobot.Connection { return b.connection.(gobot.Connection) } 93 94 func (b *ButtonDriver) update(newValue int) { 95 if newValue != b.DefaultState { 96 b.Active = true 97 b.Publish(ButtonPush, newValue) 98 } else { 99 b.Active = false 100 b.Publish(ButtonRelease, newValue) 101 } 102 }