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?

Steve Robillard
35k18 gold badges106 silver badges110 bronze badges
asked Jun 22, 2017 at 16:24
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.

Jacobm001
11.9k7 gold badges48 silver badges58 bronze badges
answered Jun 22, 2017 at 16:39
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. Commented 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. Commented Jun 22, 2017 at 17:15

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.