Skip to content

Instructions on creating a power switch for a raspberry pi

Notifications You must be signed in to change notification settings

vanderblugen/Power-Switch-For-RaspberryPi

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

10 Commits
 
 

Repository files navigation

Power Switch For A RaspberryPi

This is for adding a power switch on a RaspberryPi to trigger a script to turn off or reboot.
Information on this page was obtained from here.
This page was created for my ease of access.
Use information from this page at your own discretion.

What is needed

  • RaspberryPi
  • Momentary switch
  • Adequate wiring

Wiring in

Attach the momentary switch via wiring to GPIO pin 5 and 6 on the RaspberryPi Here's a few references

Upgrade GPIO for Python

sudo apt install python3-rpi-lgpio -y

Shutdown and reboot script

sudo nano /usr/local/bin/power-switch.py
import threading, subprocess
import RPi.GPIO as GPIO

if __name__ == '__main__':
    try:
        GPIO.setmode(GPIO.BOARD)
        GPIO.setup(5, GPIO.IN)
        GPIO.wait_for_edge(5, GPIO.RISING)
        pin = GPIO.wait_for_edge(5, GPIO.FALLING, timeout=3000)
        if pin is None:
            subprocess.call('sudo shutdown -h now', shell=True)
        else:
            subprocess.call('sudo reboot', shell=True)
    finally:
        GPIO.cleanup()

What this does

  • Push and hold for > 5 seconds shutdown the RaspberryPi
  • Push and hold for < 5 seconds reboots the RaspberryPi

Enable script at boot

sudo nano /etc/rc.local

Add a line before exit 0 to execute the script at boot.

python /usr/local/bin/power-switch.py &

Test

Be sure to test that it is functional.

Example 1 Example 2