title: Raspberry PI Button Push Listener
body: <p>Is it possible to have  button push listener in Python for the Raspberry Pi.  I have a non-latching button going to a GPIO.  I want to run some python code the first time the button is pushed.  Then I want the code to stop on the second button push no matter where it is in the first line of code.</p>
  
  <p>I've used a toggle bit variable called "flag" to register button pushes but obviously there is no listener to determine when the second push is made.</p>
  
  <pre><code>#!/usr/bin/env python
  import RPi.GPIO as GPIO
  import time
  
  Button = 16    # pin16
  
  def setup():
  
      GPIO.setmode(GPIO.BOARD)          # Numbers GPIOs by physical location
      GPIO.setup(Button, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)   # Button Input
  
  def motorcontrol():
      flag=0
      while True:
          j=GPIO.input(16)
          if j==1: #Robot is activated when button is pressed
              flag=1
              print "Robot Activated",j
          while flag==1:    
              time.sleep(5)
              print "Robot Activated for 5 seconds"
              time.sleep(5)
              print "Robot Activated for 10 seconds"
              time.sleep(5)
              print "Robot Activated for 15 seconds"
  
              j=GPIO.input(16)
              if j==1: #De activate robot on pushing the button
                  flag=0
                  print "Robot DeActivated",j
                  destroy()
  
  def destroy():
      GPIO.cleanup()                     # Release resource               
  
  if __name__ == '__main__':     # Program start from here
      setup()
      try:
          motorcontrol()
      except KeyboardInterrupt:  # When 'Ctrl+C' is pressed, the child program destroy() will be  executed.
          destroy()
  </code></pre>