Button

React to button presses without polling

Overview

GPIO pins can be leveraged to read button presses, similar to detecting motion.

The gpio.PinIn.WaitForEdge() function permits a edge detection without a busy loop.

Example

package main

import (
    "fmt"
    "log"

    "periph.io/x/conn/v3/gpio"
    "periph.io/x/conn/v3/gpio/gpioreg"
    "periph.io/x/host/v3"
)

func main() {
    // Load all the drivers:
    if _, err := host.Init(); err != nil {
        log.Fatal(err)
    }

    // Lookup a pin by its number:
    p := gpioreg.ByName("GPIO2")
    if p == nil {
        log.Fatal("Failed to find GPIO2")
    }

    fmt.Printf("%s: %s\n", p, p.Function())

    // Set it as input, with an internal pull down resistor:
    if err := p.In(gpio.PullDown, gpio.BothEdges); err != nil {
        log.Fatal(err)
    }

    // Wait for edges as detected by the hardware, and print the value read:
    for {
        p.WaitForEdge(-1)
        fmt.Printf("-> %s\n", p.Read())
    }
}

This example uses basically no CPU: the WaitForEdge() leverages the edge detection provided by the kernel, unlike other Go hardware libraries.

Buying

Buttons come in various forms and prices, here’s a selection:

The periph authors do not endorse any specific seller. These are only provided for your convenience.