I am trying to control and LED on an Raspberry Pi.
I want the LED to light up when I push a button, and maintain that state until I push the button again.
I have implemented the code below and it works quite fine. However, I am getting problems when I am not fast enough in pushing the button or hold the button.
import RPi.GPIO as GPIO
from time import sleep
inpin = 16
outpin = 20
GPIO.setmode(GPIO.BCM)
counter = 0
GPIO.setup(outpin, GPIO.OUT)
GPIO.setup(inpin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
try:
while True:
if GPIO.input(inpin):
if counter == 0:
print "port is low"
GPIO.output(outpin, 0)
counter = 0
else:
print "port is high"
GPIO.output(outpin, 1)
counter = 1
else:
if counter == 1:
print "port is low"
GPIO.output(outpin, 0)
counter = 0
else:
print "port is high"
GPIO.output(outpin, 1)
counter = 1
sleep(0.1)
finally:
GPIO.cleanup()
Implementing it the way "TessellatingHeckler" suggested works perfect. Even with multiple inputs and outputs it works perfect. Important things are the "elif" loops to guarantee fast changing states. Here's the working code:
import RPi.GPIO as GPIO
from time import sleep
GPIO.setmode(GPIO.BCM)
GPIO.setup(16, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(20, GPIO.OUT)
GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(27, GPIO.OUT)
btn1_button = 'up'
btn1_light = 'off'
btn2_button = 'up'
btn2_button = 'off'
def LED1(output):
GPIO.output(20, output)
def LED2(output):
GPIO.output(27, output)
while True:
######################## BUTTON 1 ########################
if (btn1_button == 'up' and btn1_light == 'off'):
if not GPIO.input(16):
print "LED1 ON"
LED1(1)
btn1_button = 'down'
btn1_light = 'on'
elif (btn1_button == 'down' and btn1_light == 'on'):
if GPIO.input(16):
btn1_button = 'up'
elif (btn1_button == 'up' and btn1_light == 'on'):
if not GPIO.input(16):
print "LED1 OFF"
LED1(0)
btn1_button = 'down'
btn1_light = 'off'
elif (btn1_button == 'down' and btn1_light == 'off'):
if GPIO.input(16):
btn1_button = 'up'
###########################################################
####################### BUTTON 2 ##########################
if (btn2_button == 'up' and btn2_light == 'off'):
if not GPIO.input(17):
print "LED2 ON"
LED2(1)
btn2_button = 'down'
btn2_light = 'on'
elif (btn2_button == 'down' and btn2_light == 'on'):
if GPIO.input(17):
btn2_button = 'up'
elif (btn2_button == 'up' and btn2_light == 'on'):
if not GPIO.input(17):
print "LED2 OFF"
LED2(0)
btn2_button = 'down'
btn2_light = 'off'
elif (btn2_button == 'down' and btn2_light == 'off'):
if GPIO.input(17):
btn2_button = 'up'
sleep(0.1)
###########################################################
GPIO.cleanup()