Jun-07-2019, 10:11 AM
The code works a treat in that button pressed LED ON button pressed again LED OFF. What I am trying to do is get the LED to flash when it is ON rather than permanently lit. I think I need to put in a while True loop but unsure where. Placing it in the def Loop() does make it flash but it flashes during the on and off state. Whats confusing me is the def swLed section as this is the place where the LED is turned on and off but if I put the loop in there nothing happens. Any help most appreciated - still trying to get my head around Python! Thanks
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
import RPi.GPIO as GPIO import time LedPin = 11 # pin11 --- led BtnPin = 12 # pin12 --- button Led_status = 1 def setup(): GPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical location GPIO.setup(LedPin, GPIO.OUT) # Set LedPin's mode is output 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) GPIO.output(LedPin, GPIO.HIGH) # Set LedPin high(+3.3V) to off led def swLed(ev = None ): global Led_status Led_status = not Led_status GPIO.output(LedPin, Led_status) # switch led status(on-->off; off-->on) def loop(): GPIO.add_event_detect(BtnPin, GPIO.FALLING, callback = swLed, bouncetime = 200 ) # wait for falling, set bouncetime to prevent callback function # from being called multiple times when the button is pressed while True : time.sleep( 1 ) # Don't do anything if __name__ = = '__main__' : # Program start from here setup() try : loop() except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the child program destroy() will be executed. destroy() |