haphazard.io
Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Back to homepage

Raspberry Pi GPIO power button

Wiring

Button Pin RPi GPIO
1 GPIO 3 (SCL)
2 GND

Power On

On my Raspberry Pi 2 Model B Rev 1.1, the system will power on from a halted state when shorting the SCL (GPIO 3) to Ground.

Shutdown

When the system is on, the below script will monitor SCL (GPIO 3) for a button press. When a button press is detected, the script will shutdown the Raspberry Pi safely.

Create /home/pi/scripts/shutdown.py

#!/bin/python
# Raspberry Pi button shutdown

import RPi.GPIO as GPIO
import subprocess

# Define GPIO pin number
SCL = 3

# GPIO pin setup
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(SCL, GPIO.IN, pull_up_down = GPIO.PUD_UP)

# Wait for button press
GPIO.wait_for_edge(SCL, GPIO.FALLING)

# Shutdown
subprocess.call(['sudo', 'shutdown', '-h', 'now'])

Edit /etc/rc.local adding the shutdown script before exit 0

sudo python /home/pi/scripts/shutdown.py &
exit 0

See it in action