Advertisement
learnelectronics

Button-LED.py

Sep 27th, 2017
1,103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.28 KB | None | 0 0
  1. #!/usr/bin/env python
  2. import RPi.GPIO as GPIO
  3. import time
  4.  
  5. LedPin = 11    # pin11 --- led
  6. BtnPin = 12    # pin12 --- button
  7.  
  8. Led_status = 1
  9.  
  10. def setup():
  11.     GPIO.setmode(GPIO.BOARD)       # Numbers GPIOs by physical location
  12.     GPIO.setup(LedPin, GPIO.OUT)   # Set LedPin's mode is output
  13.     GPIO.setup(BtnPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)    # Set BtnPin's mode is input, and pull up to high level(3.3V)
  14.     GPIO.output(LedPin, GPIO.HIGH) # Set LedPin high(+3.3V) to off led
  15.  
  16. def swLed(ev=None):
  17.     global Led_status
  18.     Led_status = not Led_status
  19.     GPIO.output(LedPin, Led_status)  # switch led status(on-->off; off-->on)
  20.     if Led_status == 1:
  21.         print 'led off...'
  22.     else:
  23.         print '...led on'
  24.  
  25. def loop():
  26.     GPIO.add_event_detect(BtnPin, GPIO.FALLING, callback=swLed, bouncetime=200) # wait for falling and set bouncetime to prevent the callback function from being called multiple times when the button is pressed
  27.     while True:
  28.         time.sleep(1)   # Don't do anything
  29.  
  30. def destroy():
  31.     GPIO.output(LedPin, GPIO.HIGH)     # led off
  32.     GPIO.cleanup()                     # Release resource
  33.  
  34. if __name__ == '__main__':     # Program start from here
  35.     setup()
  36.     try:
  37.         loop()
  38.     except KeyboardInterrupt:  # When 'Ctrl+C' is pressed, the child program destroy() will be  executed.
  39.         destroy()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement