I have some code which turns an led on when I hold the button. But only when I am pressing it. Could somebody help me so when I press the button then the light stays on and if I press it again the led turns off?

Here is my code -

import RPi.GPIO as GPIO
from time import sleep


sleepTime = .1

#GPIO Pin of the conponent
lightPin = 4
buttonPin = 17

GPIO.setup(lightPin, GPIO.OUT)
GPIO.setup(buttonPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.output(lightPin, False)

    while True:
        GPIO.output(lightPin, not GPIO.input(buttonPin))

    GPIO.output(lightPin, False)

There are many ways of storing state which could be applied to your code, but running a continuous loop is poor programming.

The following example is one way of doing this which doesn't involve continuous polling.


You could do similar with RPi.GPIO


This is taken from another similar post; I'm on my mobile replying so I cant post the URL easily, but in essence,

You can't read an output. Just store the state of the pin in a variable.

import RPi.GPIO as GPIO


LED = 17
ledState = False


ledState = not ledState
GPIO.output(LED, ledState)

Hope that helps.

Will try to post link later when I get time.

  • In fact you CAN read the state of an output - it will return the last value written. – Milliways Jan 5 at 3:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.