Reputation: 17
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.
Upvotes: 0
Views: 2170
Reputation: 187
If you are using gpiozero for led and button,
This is the code I have written. Not the best code but able to help you.
def onLight():
garageLed = LED(21) # Yellow LED lights up when the user is authorised
button = Button(13, pull_up=False)
reading = True;
while reading:
if (garageLed.is_lit == False):
button.wait_for_press()
button.when_pressed = ledON()
button.wait_for_release()
button.when_released = ledON()
elif (garageLed.is_lit == True):
button.wait_for_press()
button.when_pressed = ledOFF()
button.wait_for_release()
button.when_released = ledOFF()
Upvotes: 0
Reputation: 25526
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
Upvotes: 1
Reputation: 1396
Your code keeps LED one as long as button is presses.
You could implement toggle mechanism by keeping in a variable the LED state
...
ledState = False
buttonPressed = False;
...
if GPIO.input(6):
if not buttonPressed:
buttonPressed = True
ledState = not ledState
GPIO.output(13, ledState)
else
buttonPressed = False
Upvotes: 0