1

So, I am trying to use the raspberry pi model 2b with Debian to control a LED light using a button. But, when I run the python script (made with python2 btw), it brings up no errors, but instead when the button is pressed, the light does not change. An image of how I wired my pi is below.

enter image description here

And the script that I used to control the LED is here.

#!/usr/bin/env python
import RPi.GPIO as GPIO
import time

LedPin = 11
BtnPin = 12
Led_status = 1

def setup():
    GPIO.setmode(GPIO.BOARD)
    GPIO.setup(LedPin, GPIO.OUT)  
    GPIO.setup(BtnPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
    GPIO.output(LedPin, GPIO.HIGH)

def swLed(ev=None):
    global Led_status
    Led_status = not Led_status
    GPIO.output(LedPin, Led_status) 
    if Led_status == 1:
        print 'led off...'
    else:
        print '...led on'

def loop():
    GPIO.add_event_detect(BtnPin, GPIO.FALLING, callback=swLed, bouncetime=200)
    while True:
        time.sleep(1) 

def destroy():
    GPIO.output(LedPin, GPIO.HIGH)
    GPIO.cleanup()                     

if __name__ == '__main__':
    setup()
    try:
        loop()
    except KeyboardInterrupt:
        destroy()

The script did output all of the things that it was supposed to output, but the light did not change at all. Could it be because I have too much resistence (220 R). Any comments help. Thanks

2
  • The resistor has the correct value, but did you put the LED in the right way? A LED does only work in one direction.
    – Uwe Plonus
    Apr 22, 2018 at 17:14
  • If you have a close look at your LED, you should see the ring around the bottom has a flat side. That should be matched to the flat (purple wire) side in your picture. Apr 23, 2018 at 0:04

1 Answer 1

0

If the output is correct that implies that the LED is being connected to 3V3 and then 0V, so it should switch on and off.

Therefore the LED must be inserted back to front.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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