2

I hadn't programmed on my RPi for a couple of months due to me focusing mainly on my education. Yesterday, finally the school year ended, and so I decided to start programming on my Pi again from the beginning. I wired everything up correctly using my breadboard and started creating some simple programs that altered my LED's state from on to off, dimming, etc... BTW it's an RGB led. I decided to write a code that would let you choose what colour you wanted the LED to light up in, however, it doesn't seem to work.

import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BOARD)

GPIO.setup(11,GPIO.OUT)
GPIO.output(11,0)
GPIO.setup(13,GPIO.OUT)
GPIO.output(13,0)
GPIO.setup(15,GPIO.OUT)
GPIO.output(15,0)

try:
    while(True):
        request = raw_input("RGB -->")
        if (request == 1):
            GPIO.output(11,1)
        elif (request == 2):
            GPIO.output(13,1)
        elif (request == 3):
            GPIO.output(15,1)


except KeyboardInterrupt:
        GPIO.cleanup()

When I choose a colour nothing happens, can anybody help me, please?

0

1 Answer 1

3

The problem is that raw_input() function returns a string not an int. So when your code reaches the if statement you are comparing an int and a string. Since 1 (an int) does not match "1" (a string) the program reaches the end without matching any of the if or elif statements.

To fix the problem change your code to this:

if (int(request) == 1):
    GPIO.output(11,1)
elif (int(request) == 2):
    GPIO.output(13,1)
elif (int(request) == 3):
    GPIO.output(15,1)

or alternatively:

request = raw_input("RGB -->")
request = int(request)
if (request == 1):
    GPIO.output(11,1)
elif (request == 2):
    GPIO.output(13,1)
elif (request == 3):
    GPIO.output(15,1)

A good defensive programming strategy is to always include an else clause in your if statemnent. Something like this:

else:
    print("no match found")

This way your program will print an informative message rather than silently failing.

2
  • I much prefer doing the conversion once, that's far more efficient. Though your use of () in if statements is rather unpythonic. I'd suggest removing those.
    – Jacobm001
    Jun 22, 2017 at 17:12
  • @Jacobm001 I agree it is unpythonic but is based on the OP's code. The efficiency is why I included the second alternative. Jun 22, 2017 at 17:15

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.