React to button presses without polling


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.


package main

import (


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

    // 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 {

    // Wait for edges as detected by the hardware, and print the value read:
    for {
        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.


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.