1

I am having some problems getting my LED to light properly. I am using a push switch. What is happening is that when I run the code, the LED starts on, and when I press the button, it turns off. However, I want it to start start off and then turn on when I press the button. I felt like this would be an easy fix, but when I try to reverse things, it just ends up staying off and the button doesn't do anything at all. I do not believe that I have any wiring problems, it is most likely just problems with the code, because other programs that I run work ok. This is the code I am using:

import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(18, GPIO.IN, pull_up_down = GPIO.PUD_DOWN)
GPIO.setup(18, GPIO.OUT)

try:
    while False:
        GPIO.output(18,GPIO.LOW)
    while True:
        GPIO.output(18,GPIO.HIGH) 
except KeyboarrdInterrupt:
    GPIO.cleanup()
  • You need to use different GPIO for the button and the LED. while False does nothing as False is False. while True repeats the block for ever as you have no mechanism to leave the block. – joan Jan 12 '17 at 21:20
1

Take one wire of the switch and connect it to it's own gpio pin set for input. Let's say, 17.

Take the other wire from the switch, and connect it to GND.

Take the LED and connect the anode (+) to gpio 18, and the cathode (-) to GND.

Try this script.

(I do not use python, so this script is not tested, just a guess)

import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(17, GPIO.IN, pull_up_down = GPIO.PUD_UP)
GPIO.setup(18, GPIO.IN, pull_up_down = GPIO.PUD_DOWN)
GPIO.setup(18, GPIO.OUT)

try:
    while True:
        gp = GPIO.wait_for_edge(17, GPIO.BOTH, timeout=3000)
        if gp is not None:
            if GPIO.input(17):
                GPIO.output(18,GPIO.LOW)
            else:
                GPIO.output(18,GPIO.HIGH) 
except KeyboarrdInterrupt:
    GPIO.cleanup()
  • updated script after briefly reading up python syntax – Hydranix Jan 12 '17 at 22:22

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.