I watched a YouTube video where I got my button working, the code is:
Code: Select all
import RPi.GPIO as GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
#variables
atHome = 0
#Output the LED
GPIO.setup(21,GPIO.OUT)
#Input the button
GPIO.setup(17,GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
def LED(pin):
#If I click the button
if(pin==17):
#I want to turn on the led
output = 21
#if the led is high put it low
if GPIO.input(output):
GPIO.output(output,GPIO.LOW)
atHome = 0
print atHome
else:
#if low put it high
GPIO.output(output,GPIO.HIGH)
atHome = 1
print atHome
#Event for listening
GPIO.add_event_detect(17,GPIO.RISING,callback=LED,bouncetime=200)
value = input("Press Any Key To Continue")
GPIO.cleanup()
So I have setup everything and at the hearth of the program there is a try, while loop. Now I don't know where to put the event detector.
Here is the code:
Code: Select all
import RPi.GPIO as GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
#variables
atHome = 0
#Output the LED
GPIO.setup(21,GPIO.OUT)
#Input the button
GPIO.setup(17,GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
def LED(pin):
#If I click the button
if(pin==17):
#I want to turn on the led
output = 21
#if the led is high put it low
if GPIO.input(output):
GPIO.output(output,GPIO.LOW)
atHome = 0
print atHome
else:
#if low put it high
GPIO.output(output,GPIO.HIGH)
atHome = 1
print atHome
try:
while True:
GPIO.add_event_detect(17,GPIO.RISING,callback=LED,bouncetime=200)
# some other if statements here 50+ lines
except KeyboardInterrupt:
pass
print "Offline"
GPIO.cleanup()