Button project with Raspberry Pi

SONY DSCI purchased some tactile buttons to play with my Raspberry.

My first tutorial will be a very simple one. Press the button and display a message on the console.

  1. $sudo apt-get install python-dev
  2. $sudo apt-get install python-rpi.gpio

I use the second drawing below called Pull Down resistor since I want the initial value to be low. I only want an indication once I press the button.

EGHS-PullUpDownSwitchProtected

 

 

 

 

 

 

 

Please note that we are using BOARD and not BCM to position the pins of the GPIO.

With GPIO.setmode(GPIO.BOARD) the numbering of the actual RPi pins is used, e.g. pin 12 (as I use here corresponds to the Cobbler output pin named #18

#! /usr/bin/env python
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
 GPIO.setup(12, GPIO.IN)
#initialise a previous input variable to 0 (assume button not pressed last)
 prev_input = 0
 while True:
      #take a reading
      input = GPIO.input(12)
      #if the last reading was low and this one high, print
      if ((not prev_input) and input):
            print("Button pressed")
            #update previous input
            prev_input = input
            #slight pause to debounce
       time.sleep(0.05)

One additonal tweek of the code is to add an timer to measure the time inbetween each press of the button. This way we can implement a simple action by which a double-click, e.g. two consequtive presses within 1 sec will case the program to terminate.

 

#! /usr/bin/env python
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
GPIO.setup(12, GPIO.IN)
#initialise a previous input variable to 0 (assume button not pressed last)
prev_input = 0
start = time.time()
while True:
      input = GPIO.input(12)
      #if the last reading was low and this one high, print
      if ((not prev_input) and input):
            if (time.time() - start) < 1 :
                  # short double click, exit program
                  print 'Will now exit.'
                  exit()
            else :
                  tid = time.time() - start
                  print "Button pressed after %.2f s" % tid
                  start = time.time()
      #update previous input
      prev_input = input
      #slight pause to debounce
      time.sleep(0.05)