Monday, March 16, 2015

Make a hardware button to shutdown Raspberry Pi, using Python

This example show how to detect pressing on hardware button, then shutdown Raspberry Pi by calling os.system() to send command of "sudo shutdown -h now".


Connection (same as the example of "Read/Write GPIO of Raspberry Pi 2 using Python"):

shutdownPi.py
import sys
import RPi.GPIO as GPIO
import time
import os

print("sys.version:")
print(sys.version + "\n")

print("GPIO.VERSION: " + GPIO.VERSION)
print("GPIO.RPI_INFO['P1_REVISION'] = " + str(GPIO.RPI_INFO['P1_REVISION']));

io20 = 20
io21 = 21
GPIO.setmode(GPIO.BCM)
GPIO.setup(io20, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(io21, GPIO.OUT)

print("Press button to shutdown Raspberry Pi!");

def blinkLED():
    GPIO.output(io21, GPIO.HIGH)
    time.sleep(0.5)
    GPIO.output(io21, GPIO.LOW)
    time.sleep(0.5)

def shutdownRPi():
    print ("- Shutdown Raspberry Pi -")
    blinkLED()
    blinkLED()
    blinkLED()
    os.system("sudo shutdown -h now")
    GPIO.cleanup()
    exit()

try:
    while(True):
        if (not GPIO.input(io20)):
            shutdownRPi()
        time.sleep(0.1)
    
except KeyboardInterrupt:
    print ("\n")
    print ("Exit by KeyboardInterrupt\n")
  
except:
    print ("\n")
    print ("Exit by Other case!\n")
  
finally:  
    GPIO.cleanup()
    print ("Clean up GPIO\n")



No comments: