Search code examples
buttonraspberry-piraspberry-pi2led

LED will only stay turned on when the button is pushed down?


I'm trying to turn and LED on with a push button, yet it will only stay on when the button is pushed down. How can I fix this ?

below is the code I'm using:

# Import the required module. 
import RPi.GPIO as GPIO
# Set the mode of numbering the pins. 
GPIO.setmode(GPIO.BCM)
#GPIO pin 10 is the output. 
GPIO.setup(13, GPIO.OUT)
#GPIO pin 8 is the input. 
GPIO.setup(6, GPIO.IN)
#Initialise GPIO13 to low (False) so that the LED is off. 
GPIO.output(13, False)
while 1:
    if GPIO.input(6):
        GPIO.output( 13, True)
    else:
        GPIO.output( 13, False)
#keep LED on till the button pressed again then it turns off?

[Edit] When I run the code the led starts off (as I want it to be) then when the button is pressed the led turns on, but it only stays on while the button is held down. I want it to be one press turns the led on, and it will stay on till the button is pressed again.


Solution

  • Try this:

    isPressed = False
    isOn = False
    while 1:
        if GPIO.input(6):
            isPressed = True
        elif isPressed:
            isOn = not isOn
            GPIO.output( 13, isOn)
            isPressed = False
    

    This toggles on releasing the button (default button behaviour on most OS). The other way round:

    isPressed = False
    isOn = False
    while 1:
        if GPIO.input(6):
            if not isPressed:
                isPressed = True
                isOn = not isOn
                GPIO.output( 13, isOn)
        else:
            isPressed = False