Last Friday I got some spare time (finally!) and, with the help and tools of my friend Alfredo, we placed a button in the RaspberryPi case so, when I push it, a custom command its executed on the RaspberryPi, like for example, a clean system shutdown.

First lets start with some pictures of the final result:


And now the schematics (pins used in the schematics are 3.3v, GND and GPIO):

raspberry_gpio_button

We mainly followed this post, but used a different GPIO port, we soldered the components (once we tested the schematics on a protyping board) and modified the code to launch a custom command. This is the resulting code we used to do a system shutdown (I removed some comments from the original code of the post):

import os
import time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(4,GPIO.IN)

prev_input = 0
while True:
  input = GPIO.input(4)
  if ((not prev_input) and input):
    os.system("sudo halt")
  prev_input = input
  #slight pause to debounce
  time.sleep(0.05)

The line highlighted is the one you should modify to set your custom command. To test it, you have to execute it as root:

$ sudo python gpio_button.py

and press the button. Finally, to launch this code in the startup process, just add it to /etc/rc.local (just before the exit 0):

$ sudo vi /etc/rc.local

Easy peasy!

Next steps: modify the program to detect single click, double-click and long click.