Raspberry Pi lights the wrong led

Asked

Viewed 33 times

-3

I am making a practical experience in which I turn on a green led or an red as the result of a question. I’m sure it’s not the circuits' problem, because I’ve tried it in many ways and it’s always the same: the led that is lit is always red. Here’s the code I used:

import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
def led(pin):
    GPIO.output(pin,GPIO.HIGH)
    time.sleep(3)
    GPIO.output(pin,GPIO.LOW)
GPIO.setup(12,GPIO.OUT)
GPIO.setup(16,GPIO.OUT)
print "How much is 2+2?"
awnser=raw_input(" >")
if awnser==4:
    led(16)
else:
    led(12)
GPIO.cleanup()

Can someone help me? Thank you.

  • Checked if there was no confusion between the configuration of GPIO.BOARD and GPIO.BCM?

  • raw_input always returns a string and will never be equal to integer 4, because '4' is different from 4.

1 answer

3


awnser=raw_input(" >")
if awnser==4:
    led(16)
else:
    led(12)

The condition awnser==4 will never be satisfied, because the function raw_input at all times returns a string and Python differentiates between '4' of 4.

You will then need to convert the value to integer before comparing it:

awnser = int(raw_input('> '))

Just be careful that an exception will be made ValueError if the value entered by the user cannot be converted to an integer, such as a letter, for example.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.