GPIO pins can be leveraged to detect motion via a PIR (Passive/Pyroelectric InfraRed sensor), similar to reading button presses.
The gpio.PinIn.WaitForEdge() function permits a edge detection without a busy loop.
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, err := gpioreg.ByName("16")
if err != nil {
log.Fatal(err)
}
fmt.Printf("%s: %s\n", p, p.Function())
// Set it as input.
if err = p.In(gpio.PullNoChange, gpio.RisingEdge); err != nil {
log.Fatal(err)
}
// Wait for edges as detected by the hardware.
for {
p.WaitForEdge(-1)
if p.Read() == gpio.High {
fmt.Printf("You moved!\n")
}
}
}
This example uses basically no CPU: the WaitForEdge() leverages the edge detection provided by the kernel, unlike other Go hardware libraries.
The periph authors do not endorse any specific seller. These are only provided for your convenience.