Created
June 2, 2021 13:41
-
-
Save danesparza/f4b47ee101fa2557d38c8e0a005615e9 to your computer and use it in GitHub Desktop.
Motion detection using Raspberry Pi and a PIR
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"flag" | |
"fmt" | |
"os" | |
"time" | |
"github.com/stianeikeland/go-rpio" | |
) | |
func main() { | |
// Defaults to GPIO pin 23 (NOT physical pin 23) | |
// but you can pass any pin | |
// See https://pinout.xyz for more information on GPIO pin layout | |
// Need a PIR sensor? I used this one: https://www.adafruit.com/product/189 | |
pinNumber := flag.Int("pin", 23, "GPIO pin") | |
flag.Parse() | |
if err := rpio.Open(); err != nil { | |
fmt.Println(err) | |
os.Exit(1) | |
} | |
defer rpio.Close() | |
pin := rpio.Pin(*pinNumber) | |
pin.Mode(rpio.Input) | |
// Store the 'last reading' | |
// Initially, set it to the 'low' (no motion) state | |
lr := rpio.Low | |
// The big loop | |
for { | |
// Read from the sensor | |
v := pin.Read() | |
// Latch / unlatch check | |
if lr != v { | |
lr = v | |
if lr == rpio.High { | |
fmt.Printf("Motion detected!\n") | |
} | |
if lr == rpio.Low { | |
fmt.Printf("Motion reset\n") | |
} | |
} | |
// Sleep for a second | |
time.Sleep(time.Millisecond * 100) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment