Skip to content

Instantly share code, notes, and snippets.

@larryli
Last active August 16, 2017 08:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save larryli/1506e3fa0ef6ef511e7f5483afc79fc2 to your computer and use it in GitHub Desktop.
Save larryli/1506e3fa0ef6ef511e7f5483afc79fc2 to your computer and use it in GitHub Desktop.
Orange Pi Zero TTP224
package main
import (
"fmt"
"github.com/davecheney/gpio"
"os"
"os/signal"
"time"
)
type Buttons struct {
pins []gpio.Pin
}
func NewButtons(numbers ...int) (*Buttons, error) {
buttons := &Buttons{
pins: make([]gpio.Pin, len(numbers)),
}
for no, number := range numbers {
pin, err := gpio.OpenPin(number, gpio.ModeInput)
if err != nil {
return nil, err
}
buttons.pins[no] = pin
}
return buttons, nil
}
func (b *Buttons) Watch(callback func(no int, pressed bool)) error {
for n, p := range b.pins {
no := n
pin := p
if err := pin.BeginWatch(gpio.EdgeBoth, func() {
callback(no, pin.Get())
}); err != nil {
return err
}
}
return nil
}
func (b *Buttons) Close() error {
for _, pin := range b.pins {
if err := pin.EndWatch(); err != nil {
return err
}
if err := pin.Close(); err != nil {
return err
}
}
return nil
}
// 3.3V+ [1] (2) 5V+ ==> TTP224 VCC
// IIC SDA / GPIO12 (3) (4) 5V+
// IIC SCL / GPIO11 (5) (6) GND ==> TTP224 GND
// GPIO6 (7) (8) GPIO198 / UART2 TX
// GND (9) (10) GPIO199 / UART2 RX
// TTP224 OUT2 <== GPIO1 (11) (12) GPIO7 ==> TTP224 OUT1
// TTP224 OUT3 <== GPIO0 (13) (14) GND
// TTP224 OUT4 <== GPIO3 (15) (16) GPIO19
// 3.3V+ (17) (18) GPIO18
// GPIO15 (19) (20) GND
// GPIO16 (21) (22) GPIO2
// GPIO14 (23) (24) GPIO13
// GND (25) (26) GPIO10
func main() {
buttons, err := NewButtons(gpio.GPIO7, gpio.GPIO1, gpio.GPIO0, gpio.GPIO3)
if err != nil {
fmt.Printf("Error init buttons: %s\n", err)
return
}
// clean up on exit
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
go func() {
for _ = range c {
fmt.Println("Closing buttons and terminating program.")
buttons.Close()
os.Exit(0)
}
}()
err = buttons.Watch(func(no int, pressed bool) {
fmt.Printf("Button #%d: ", no)
if pressed {
fmt.Println("pressed.")
} else {
fmt.Println("released.")
}
})
if err != nil {
fmt.Printf("Unable to watch buttons: %s\n", err.Error())
os.Exit(1)
}
fmt.Printf("Now watching buttons:\n")
for {
time.Sleep(2000 * time.Millisecond)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment