1// SPDX-FileCopyrightText: 2020 Kent Gibson <warthog618@gmail.com>
2//
3// SPDX-License-Identifier: MIT
4
5//go:build linux
6// +build linux
7
8// A simple example that watches an input pin and reports edge events.
9
10package main
11
12import (
13 "fmt"
14 "os"
15 "syscall"
16 "time"
17
18 "github.com/warthog618/gpiod"
19 "github.com/warthog618/gpiod/device/rpi"
20)
21
22func eventHandler(evt gpiod.LineEvent) {
23 t := time.Now()
24 edge := "rising"
25 if evt.Type == gpiod.LineEventFallingEdge {
26 edge = "falling"
27 }
28 if evt.Seqno != 0 {
29 // only uAPI v2 populates the sequence numbers
30 fmt.Printf("event: #%d(%d)%3d %-7s %s (%s)\n",
31 evt.Seqno,
32 evt.LineSeqno,
33 evt.Offset,
34 edge,
35 t.Format(time.RFC3339Nano),
36 evt.Timestamp)
37 } else {
38 fmt.Printf("event:%3d %-7s %s (%s)\n",
39 evt.Offset,
40 edge,
41 t.Format(time.RFC3339Nano),
42 evt.Timestamp)
43 }
44}
45
46// Watches GPIO 23 (Raspberry Pi J8-16) and reports when it changes state.
47func main() {
48 offset := rpi.J8p11
49 l, err := gpiod.RequestLine("gpiochip0", offset,
50 gpiod.WithPullUp,
51 gpiod.WithBothEdges,
52 gpiod.WithEventHandler(eventHandler))
53 if err != nil {
54 fmt.Printf("RequestLine returned error: %s\n", err)
55 if err == syscall.Errno(22) {
56 fmt.Println("Note that the WithPullUp option requires kernel V5.5 or later - check your kernel version.")
57 }
58 os.Exit(1)
59 }
60 defer l.Close()
61
62 // In a real application the main thread would do something useful.
63 // But we'll just run for a minute then exit.
64 fmt.Printf("Watching Pin %d...\n", offset)
65 time.Sleep(time.Minute)
66 fmt.Println("exiting...")
67}