Pergunta

I'm new to python and i've written some code for the GPIO pins on my Raspberry Pi but when i run it i get this:

user@pi:~$ sudo python change.py
Which GPIO do you whant to change? 13
Exit (y/n) n
Traceback (most recent call last):
  File "change.py", line 36, in <module>
    runGPIO()
  File "change.py", line 31, in runGPIO
    var_input2 = input ("Exit (y/n) ")
  File "<string>", line 1, in <module>
NameError: name 'n' is not defined

Because i'm new to python i can' seem to find any errors - even with error checkers so i'm a bit puzzled The Code is...

import sys
import RPi.GPIO as GPIO
GPIO.setup(13, GPIO.OUT)
GPIO.setup(15, GPIO.OUT)
GPIO.setup(16, GPIO.OUT)
GPIO.output(13, True)
GPIO.output(15, True)
GPIO.output(16, True)
var13 = True
var15 = True
var16 = True
def runGPIO():
    var_input = input ("Which GPIO do you whant to change? ")
    if (var_input == 13) or (var_input == 2):
        if var13 == True:
            GPIO.output(13, False)
        else:
            GPIO.output(13, True)
    elif (var_input == 15) or (var_input == 3):
        if var15 == True:
            GPIO.output(15, False)
        else:
            GPIO.output(15, True)
    elif (var_input == 16) or (var_input == 4):
        if var16 == True:
            GPIO.output(16, False)
        else:
            GPIO.output(16, True)
    else:
        print "Please enter a valid GPIO pin number"
    var_input2 = input ("Exit (y/n) ")
    if var_input2 == "y":
        sys.exit()a
    else:
        return
runGPIO()

The code set's up 3 GPIO pins (which turns them on). The code then turns all the LED's off before asking the user which LED to turn on or off

Any help suggestions for improvements etc would be greatly appreciated

Thanks

Foi útil?

Solução

It looks like you're using Python 2.x, which is fine for the time being as long as it is 2.7.3.

In version 2.x you need to use raw_input("Enter (y/n): ") if you are grabbing text.

input() in this version would evaluate the input.

Outras dicas

input() in 2.x interprets its input as Python code. Use raw_input() instead.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top