I am trying to create a program which which switch an LED ON or OFF when a switch is pressed. The following is the circuit diagram
The python code is
import RPi.GPIO as GPIO
is_lamp_on = False
try:
GPIO.setmode(GPIO.BOARD)
GPIO.setup(11,GPIO.OUT)
GPIO.setup(12,GPIO.IN,pull_up_down=GPIO.PUD_UP)
GPIO.output(11,GPIO.LOW) #lamp is initially off
print ('initial lamp is ', is_lamp_on)
print ('initial input 12 is ', GPIO.input(12))
while True:
if GPIO.input(12)==GPIO.LOW: #button pressed down but not released yet
print(' button pressed but not released')
print ('input 12 is ', GPIO.input(12))
while True: #wait for button to be released
if GPIO.input(12)==GPIO.HIGH: #button released
print(' button released, old lamp state is ',is_lamp_on)
if(is_lamp_on == True): # lamp was ON when button is released
GPIO.output(11,GPIO.LOW) #lamp off
is_lamp_on = False;
print('new lamp state before break ', is_lamp_on)
break
else: #lamp is not ON
GPIO.output(11,GPIO.HIGH)
is_lamp_on = True;
print('new lamp state before break ', is_lamp_on)
break
except KeyboardInterrupt:
GPIO.cleanup()
If I do quick on/off then the LED gets on and off correctly. However, if I keep the switch pressed for longer then the LED doesn't work properly (for eg, if LED was ON then after a 2-3 second long press, the LED stays on
I found that the loop seem to execute multiple times if the switch is pressed on for longer
Pi@raspberrypi:~/kabir $ python manu_lamp_program.py
('initial lamp is ', False)
('initial input 12 is ', 1)
---0 SHORT PRESS
button pressed but not released
('input 12 is ', 0)
(' button released, old lamp state is ', False)
('new lamp state before break ', True)
---1 SHORT PRESS
button pressed but not released
('input 12 is ', 0)
(' button released, old lamp state is ', True)
('new lamp state before break ', False)
-----2 LONG PRESS, the code seem to have run multiple times
button pressed but not released
('input 12 is ', 0)
(' button released, old lamp state is ', False)
('new lamp state before break ', True)
button pressed but not released
('input 12 is ', 0)
(' button released, old lamp state is ', True)
('new lamp state before break ', False)
What am I doing wrong?
if GPIO.input(12)