3

I'm a beginner to the raspberry pi and python.

I want the pi to act like a flip flop to the led so that when i push the button once, it will turn on and if I push it again, it will turn off and so on.

How can I do this.

So far, part of the code...

while true:
  if (GPIO.input(11) == 1):
    if (status == 0):
      GPIO.output(22, 0)
      status = 1

    if (status == 1):
      GPIO.output(22, 1)
      status = 0
5
  • 1
    You could replace if (status == 1): with else:
    – joan
    Jun 11, 2014 at 12:58
  • I am not a Python programmer, but the code you have listed makes no allowance for contact bounce which is ubiquitous. You will find other answers on this site which address this. You may also want to refer to the Magpi which has useful beginner tutorials.
    – Milliways
    Jun 11, 2014 at 13:07
  • What sort of button - does it stay on until you press it again, or is it only on while you press it?
    – Wilf
    Jun 11, 2014 at 14:46
  • @Wilf The button stays on if you hold on it. If you let go, it will go off. Jun 12, 2014 at 8:00
  • i think the script should work for that - you may need to hold it for atleast 0.2 seconds, as set by the sleep bit at the bottom
    – Wilf
    Jun 12, 2014 at 10:50

9 Answers 9

6

You can also use interrupts, which are quite useful in many other settings as well. This way, you can have your script do other things while you play with the button and the LED.

import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BOARD)

GPIO.setup(22, GPIO.OUT) # LED
GPIO.setup(11, GPIO.IN) # Button

def toggleLEDcallback(channel):
    if (GPIO.input(22) == True):
        GPIO.output(22, False)
    else:
        GPIO.output(22, True)

# detects rising edge on button. ignores multiple rising edges in 100ms
GPIO.add_event_detect(11, GPIO.RISING, callback=toggleLEDcallback, bouncetime=100) 

while 1:
    ...
    # do some other stuff
    ...
GPIO.cleanup()
1
  • Awesome! Took a little to understand, but works fantastic. Will try to add my slant on it below, with wiring connections to a momentary button & 10K resistor and a LED & 220 ohm resistor.
    – Abisdad
    Nov 6, 2020 at 9:20
1

This is the code I used and mine work flawlessly

import RPi.GPIO as GPIO
from time import sleep
GPIO.setmode(GPIO.BOARD)
GPIO.setup(11, GPIO.IN) #BUTTON
GPIO.setup(15, GPIO.OUT) #LED
state = 0
while True:
      input = GPIO.input(11)
      if (input == False): #have to press button to work
              if (state == 1):  #this is on so led will start in off
                    GPIO.output(15, True)
                    print("Led On")
                    state = 0
              elif (state == 0):  #Led will start at this position which is off
                    GPIO.output(15, False)
                    print("Led On")
                    state = 1
              sleep(0.1)
1
  • For future reference, in the editing menu there's a button with a pair of curly brackets {}. Insert your code just like you did, highlight it all, and then click that button.
    – Jacobm001
    Mar 29, 2015 at 22:51
1

None of the other answers in this thread worked for what I was trying to do. I have a momentary switch, "on push" I wanted the pin changed to high if it was low and changed to low if it was high.

It seems that is what the OP was trying to do also. The other examples made the LED flash

My code uses GPIO pin#'s instead of the board #'s

import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)

GPIO.setup(20, GPIO.IN, pull_up_down=GPIO.PUD_UP) 
GPIO.setwarnings(False)
GPIO.setup(25,GPIO.OUT)
GPIO.output(25,GPIO.LOW) # start with the output LOW
while True:
    input_state = GPIO.input(20)
    if input_state == False: #on push
        if GPIO.input(25):   # checks if the pin is HIGH
            GPIO.output(25,GPIO.LOW)
            print('Off')
        else:
            GPIO.output(25,GPIO.HIGH)
            print('On')
        time.sleep(0.5)
2
  • Some explanation and/or context would be useful to include in your answer.
    – Darth Vader
    Dec 9, 2017 at 15:14
  • Yes, I should have done that to begin with. Thanks
    – mark2326
    Dec 9, 2017 at 19:23
0

I haven't tested this, but something like this might work (if not you should be able to get the idea of it....):

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

GPIO.setmode(GPIO.BOARD)

GPIO.setup(22, GPIO.OUT)
GPIO.setup(11, GPIO.IN)

#the above bit of script sets up the required modules and stuff

state = 0

while True:

    if ( GPIO.input(11) == True ):
        if (state == 1):
            state = 0
        elif (state == 0):
            state = 1

    if (state == 1):
        print("Output On")
        GPIO.output(22, True)
    elif (state == 0):
        print("Output Off")
        GPIO.output(22, False)

    sleep(0.2)

First, it checks whether the switch is on, and changes state if the switch is on. Then it should turn on or turn off the output accordingly, as well as printing what is doing, useful in the case of dodgy wiring.

Also when I do scripts on the Pi, and want to do something else with it afterwards without rebooting, I do a cleanup script top run afterwards, or after a script has crashed due to an error. In the case it should be something like:

#!/usr/bin/env python
import RPi.GPIO as GPIO
import os
import sys
from time import sleep

GPIO.setmode(GPIO.BOARD)

GPIO.setup(22, GPIO.OUT)

while True:
    GPIO.output(22, False)
    print "This should now finish"
    GPIO.cleanup()
    sys.exit()

I haven't had much chance to do Python for a while, so this should work...

0

I've been trying to get this to work so when you press the button the LED turns on and Stays On,then when you press it again it turns off.. this is the closest I've got so far but the switch seem unreliable and sometimes works as i want then other times it doesn't... can anyone help here??

import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
GPIO.setup(25, GPIO.OUT) 
GPIO.setup(7, GPIO.IN) 
GPIO.output(25, True) 

while True:

      if(GPIO.input(7) == 1):
          GPIO.output(25, 0)

          if(GPIO.input(7) ==0):
             GPIO.output(25, 1)
0
0

I've devleoped this from Bill Kronholm's above: # Toggle a latching momentary button, using interrupts on the RPi. # Developed from: how to turn on and off an led with only a tactile button # By Bill Kronholm - 12-June-2014 # Documentation: https://sourceforge.net/p/raspberry-gpio-python/wiki/Inputs/ # This version by Rob Thomas, Digi Teacher, Glenunga International High School, South Australia # 6-Nov-2020 Ver 2.0

import time 
import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)

# *********   Wiring connections:
# Pin 2 - 5V to one side of button.
# Pin 12 - GPIO18 to other side of button and one side of a 10K resistor.
# Pin 6 - GND to the other side of 10K resistor.
# Pin 11 - GPIO17 to long leg of LED.
# Short leg of LED to one side of 220 ohm resistor.
# Pin 9 - GND to other side of 220 ohm resistor.

butt = 18 # Pin 12 
LED = 17  # Pin 11
GPIO.setup(LED,GPIO.OUT)
GPIO.setup(butt,GPIO.IN)

def toggleLEDcallback(channel):
    if (GPIO.input(LED) == True):
        GPIO.output(LED, False)
        print("LED on!")
    else:
        GPIO.output(LED, True)
        print("LED off!")

# Next line detects rising edge on button. Ignores multiple rising edges in 100ms.
# This indepedantly detects when a button is pressed and toggles the LED on/off
GPIO.add_event_detect(butt, GPIO.RISING, callback=toggleLEDcallback, bouncetime=100) 

# Loop to do other stuff in the loop...
while True:
    print(".....")
    time.sleep(1)
GPIO.cleanup()   # Cleans up the used ports on RPi.
0

This works for me

import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)

led = 18
button = 23
state = 0

GPIO.setup(led,GPIO.OUT)
GPIO.setup(button,GPIO.IN, pull_up_down=GPIO.PUD_UP)

try:
    while True:
        if(GPIO.input(button) == False):
              if(state == 0):
                  state = 1
              elif(state == 1):
                   state = 0

        if(state == 0):
            GPIO.output(led,True)
            time.sleep(0.1)

        elif(state == 1):
             GPIO.output(led,False)
             time.sleep(0.1)

finally:
    print("Cleaning up")
    GPIO.cleanup()
-1

good answer

pull up switch
   while True:
   if(GPIO.input==0):
    time.sleep(1)
    flag=flag+1
    if(flag==1)
     led on
    if flag==2
   led off
   flag=0
1
  • 1
    This is just flat-out wrong. It is badly indented, badly coded and contains non-Python code.
    – recantha
    Dec 19, 2015 at 9:15
-3

Your going to have to have something thats holds the value of the current state and then compare that state with the new state of someone pushing the button. You will need a software or hardware debounce like Milliways pointed out.

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.