1

Hello I need some help with my leds, I have 2 leds one green and one red. What I want to do is just turn on the green led (and turn off the red) when I press a push button, that is to say all the time that I'm waiting, the red led will be on and the green off and when I push the button they will change their value.

import cv2
import os
import time
import dlib
import RPi.GPIO as GPIO

# Raspberry settings
GPIO.setmode(GPIO.BCM)

btn, red_led, green_led, slider_on = 20, 26, 21, 19

GPIO.setup(slider_on, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(btn, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(red_led, GPIO.OUT)
GPIO.setup(green_led, GPIO.OUT)


# Main function
def main():
    # Inicialize variables
    cap = cv2.VideoCapture(0)

    try:
        while (True):
            slider_true = GPIO.input(slider_on)

            if slider_true == 1:
                # Configure leds.
                GPIO.output(green_led, GPIO.HIGH)
                GPIO.output(red_led, GPIO.LOW)

                # Wait until the button is pressed.
                btn_press = not GPIO.input(btn)
                if btn_press == True:
                    print('Btn pressed')
                    break

            else:
                GPIO.output(red_led, GPIO.HIGH)
                GPIO.output(green_led, GPIO.LOW)
                cv2.destroyAllWindows()

    finally:
        # To ending we clean GPIOS, close the windows and release resources.
        GPIO.cleanup()



# Execute the main function
if __name__ == '__main__':
    main()

The problem is that, every time I run the program a few seconds the green led is on and the red is off and these seconds the green led turn off and the red turn on as it should be from the beginning. Why happens this?

Thank you very much.

2

I guess the reason why you observe this behaviour in the first seconds is that you don't initialize the output state of the led pins. So, those gpios are in a default state (usually it's LOW, but it might be different for specific pins and depend on other configurations). It will take a while until cap is initialized and that's the delay you see at the beginning of your program. If I'm right, you just have to initialize the led pins to whatever state you want at the beginning.

  • Yes I supposed the same as you and finally the solution was declare they low at the beginning after the "raspberry settings" – Lleims Jun 28 '19 at 13:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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