forked from warthog618/go-gpiocdev
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwatcher.go
66 lines (59 loc) · 1.51 KB
/
watcher.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
// SPDX-FileCopyrightText: 2020 Kent Gibson <[email protected]>
//
// SPDX-License-Identifier: MIT
//go:build linux
// +build linux
// A simple example that watches an input pin and reports edge events.
package main
import (
"fmt"
"os"
"syscall"
"time"
"github.com/warthog618/gpiod"
"github.com/warthog618/gpiod/device/rpi"
)
func eventHandler(evt gpiod.LineEvent) {
t := time.Now()
edge := "rising"
if evt.Type == gpiod.LineEventFallingEdge {
edge = "falling"
}
if evt.Seqno != 0 {
// only uAPI v2 populates the sequence numbers
fmt.Printf("event: #%d(%d)%3d %-7s %s (%s)\n",
evt.Seqno,
evt.LineSeqno,
evt.Offset,
edge,
t.Format(time.RFC3339Nano),
evt.Timestamp)
} else {
fmt.Printf("event:%3d %-7s %s (%s)\n",
evt.Offset,
edge,
t.Format(time.RFC3339Nano),
evt.Timestamp)
}
}
// Watches GPIO 23 (Raspberry Pi J8-16) and reports when it changes state.
func main() {
offset := rpi.J8p16
l, err := gpiod.RequestLine("gpiochip0", offset,
gpiod.WithPullUp,
gpiod.WithBothEdges,
gpiod.WithEventHandler(eventHandler))
if err != nil {
fmt.Printf("RequestLine returned error: %s\n", err)
if err == syscall.Errno(22) {
fmt.Println("Note that the WithPullUp option requires kernel V5.5 or later - check your kernel version.")
}
os.Exit(1)
}
defer l.Close()
// In a real application the main thread would do something useful.
// But we'll just run for a minute then exit.
fmt.Printf("Watching Pin %d...\n", offset)
time.Sleep(time.Minute)
fmt.Println("exiting...")
}