0

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 -

#button.py
import RPi.GPIO as GPIO
from time import sleep

GPIO.setmode(GPIO.BCM)

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)

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

finally:
    GPIO.output(lightPin, False)
    GPIO.cleanup()
2

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.

https://projects.raspberrypi.org/en/projects/physical-computing/9

You could do similar with RPi.GPIO

0

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

GPIO.setmode(GPIO.BCM)

LED = 17
ledState = False

GPIO.setup(LED,GPIO.OUT)

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 acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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