0

I am trying to execute the code where the LED will be blinking until the button is pressed. Once the button is pressed, the LED should be 'On' without blinking. The issue is that the LED keeps blinking even when the button is pressed. Here is my code:

import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(17,GPIO.OUT)
GPIO.setup(2, GPIO.IN, pull_up_down=GPIO.PUD_UP)

while True:
        GPIO.output(17,True)
        time.sleep(1)
        GPIO.output(17, False)
        time.sleep(1)
        button_state=GPIO.input(2)
        if button_state==True:
                    GPIO.output(17, True)  
2
  • Not Pi specific. This is a general Python question.
    – joan
    Commented Jul 15, 2018 at 9:12
  • Yes, it is a general programming question. But the OP is new to this and might have trouble separating the general code from the Raspberry Pi specific things,
    – NomadMaker
    Commented Jul 15, 2018 at 9:26

2 Answers 2

2

According to the code above, the "while True" does the following, in order. I'm ignoring the "sleep()" calls for this.

To get a better idea, you'd need to edit the question to add a circuit for your buttons and LED. The only thing this might change in my answer is if the button is high when it is pressed, or low when it is pressed.

  1. Turn on the LED
  2. Turn off the LED
  3. Is pin 2 true?
  4. If so, then turn on the LED

These same four steps keep being executed in order, until you stop the program.

You need to change step four. I think the best way to do this is to break out of the while loop (with a break statment) and create a second while loop right after the first, which just has "while True:" and doesn't do anything but that. It's just there to keep the program from ending.

What I'd do is to rewrite the end of your first while loop as:

    while True:
       ... Turn the LED on and off ...
       if GPIO.input(2) == True:
          break // exit the while loop

   GPIO.output(17, True)  // turn on the LED
   while True:
      // Don't do anything

That's it. A second while loop will keep the LED on. You don't need a variable to store the button state information because you only check it once.

0

It blinks because you have told it to blink.

The while loop continues to execute after the lines

   if button_state==True:
      GPIO.output(17, True)

The simplest "fix" is to add the following lines.

   if button_state==True:
      GPIO.output(17, True)
      while GPIO.input(2) == True:
         time.sleep(0.1)

That will not continue the outer while loop until the button is released.

Your Answer

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

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