Advertisement
Guest User

Untitled

a guest
Jul 23rd, 2019
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.66 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. ########################################################################
  3. # Filename    : ButtonLED.py
  4. # Description : Controlling an led by button.
  5. # Author      : freenove
  6. # modification: 2018/08/02
  7. ########################################################################
  8. import RPi.GPIO as GPIO
  9. import time
  10.  
  11. ledPin = 11    # define the ledPin
  12. buttonPin = 12    # define the buttonPin
  13.  
  14. def setup():
  15.     print ('Program is starting...')
  16.     GPIO.setmode(GPIO.BOARD)       # Numbers GPIOs by physical location
  17.     GPIO.setup(ledPin, GPIO.OUT)   # Set ledPin's mode is output
  18.     GPIO.setup(buttonPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)    # Set buttonPin's mode is input, and pull up to high level(3.3V)
  19.  
  20. def loop():
  21.     led = GPIO.input(ledPin)
  22.     btnWas = GPIO.input(buttonPin)
  23.     t = time.clock()
  24.     while True:
  25.         btn = GPIO.input(buttonPin)
  26.         if btn != btnWas :
  27.             # remember button
  28.             btnWas = btn
  29.             print('button: %d' %btn)
  30.            
  31.             if btn == GPIO.LOW :
  32.                 if time.clock() - t < 0.2 :
  33.                     print ("button: blink")
  34.                     for i in range(1, 5):
  35.                         GPIO.output(ledPin, GPIO.HIGH)
  36.                         time.sleep(0.5)
  37.                         GPIO.output(ledPin, GPIO.LOW)
  38.                         time.sleep(0.5)
  39.                    
  40.                    
  41.                 t = time.clock()
  42.                                
  43.                 # change LED
  44.                 if led == GPIO.LOW :
  45.                     led = GPIO.HIGH
  46.                 else :
  47.                     led = GPIO.LOW
  48.                 GPIO.output(ledPin, led)
  49.  
  50. def destroy():
  51.     GPIO.output(ledPin, GPIO.LOW)     # led off
  52.     GPIO.cleanup()                     # Release resource
  53.  
  54. if __name__ == '__main__':     # Program start from here
  55.     setup()
  56.     try:
  57.         loop()
  58.     except KeyboardInterrupt:  # When 'Ctrl+C' is pressed, the child program destroy() will be  executed.
  59.         destroy()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement