0

This is a very simple question that I could not find the answer to via google. I just want to have an input, such as typing Green to turn on a green LED. Here is my code so far.

import RPi.GPIO as GPIO
import time
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(21,GPIO.OUT)
GPIO.setup(26,GPIO.OUT)
GPIO.setup(17,GPIO.OUT)



Green = 'GPIO.output(17, True)'

input ()

Typing in green just says the string back. Without the '', it just runs the script and turns the LED on. Thanks for your hlep.

  • What search terms did you use? It’s odd that you couldn’t find anything relevant on google. – AMC Dec 04 '19 at 02:41

2 Answers2

0

You need to capture your input in a variable, like so: color = input()

Then you can plumb that input through some logic:

if color.lower() == 'green':
    GPIO.output(17, True)

Here, I forced the input to be lowercase, so we only account for the input as if it were entered in lowercase, for easy comparison of strings since "Green" != "green"

Because there may still be confusion, I amended this answer with the following two examples:

A more complicated example, using a dictionary:

def set_color_green():
    # Sets green by calling the output function to the gpio object
    GPIO.output(17, True)

# construct a dictionary with valid values
gpio_func_dict = {'green': set_color_green} # Here, all we need is a function name

color = input()

# guard against capital letters
if color.lower() not in gpio_func_dict.keys():
    raise Exception('You provided an invalid option')

# Call the right function
gpio_func_dict[color.lower()]()

And a dangerous example using the string...

if color.lower() == 'green':
    exec(Green) # getting in the habit of doing this could lead to a long career of security flaws, vulnerabilities, and bugs
dddJewelsbbb
  • 626
  • 4
  • 17
  • Can you explain to me what input.lower is? Im super new to python, I apologize. – Zach Davis Dec 04 '19 at 01:33
  • I get this error. Traceback (most recent call last): File "/home/pi/Desktop/control.py", line 14, in if input.lower() == 'Green': AttributeError: 'builtin_function_or_method' object has no attribute 'lower' – Zach Davis Dec 04 '19 at 01:33
  • So, perhaps it's a wise idea to use a different variable name, like `color =` instead of `input =`, but that error shouldn't happen unless you don't create an `input`. Are you actually doing `input = input()` before you call `input.lower()`? – dddJewelsbbb Dec 04 '19 at 01:35
  • I created the input, however my output is just sending back the code I typed in.>>> Green 'GPIO.output(26, True)' – Zach Davis Dec 04 '19 at 01:40
  • This is python 2 by the way. – Zach Davis Dec 04 '19 at 01:40
  • I missed that this was Python2.x, but was surprised to find that masking a builtin like that didn't work in Python2.x. Regardless, I still don't understand your confusion -- perhaps I need to update my answer to add additional information. I think there's an expectation of executing a string -- which is possible if done a specific way, but is really a bad habit – dddJewelsbbb Dec 04 '19 at 01:44
  • Also, as a disclaimer: I never deal with GPIO. I assumed your issue was that you were calling `Green` inline or something like that. – dddJewelsbbb Dec 04 '19 at 01:45
  • Basically, I want python to execute something based off of the input I type in, I assume I would need to assign a variable, green in this case, to output my command in python. The GPIO command is just GPIO.output(17, True). By learning to do this, I hope to be able to go further in python/pi programming. – Zach Davis Dec 04 '19 at 01:52
  • @ZachDavis If you just want to _output_ it to the screen, then fine, print it. But if you want to _execute_ it, the example I have above should be more than sufficient to do just that. I'll even throw in a more complex example, AND a dangerous example! – dddJewelsbbb Dec 04 '19 at 01:53
  • @ZachDavis hth, I added two more examples of different ways to do what you're asking. The one in the middle is more "complete", whereas the last one is a modification to the if statement in the original. Definitely be careful, and doing the last one is *for educational purposes only*, I wouldn't get in the habit of doing that, because exec could be extremely dangerous under the right circumstances. – dddJewelsbbb Dec 04 '19 at 02:02
0

It's best to use constants for your GPIO pin numbers. Then when you say change the green-LED to another pin, the code only needs to be changed at a single point.

I moved the GPIO setup code into a single function, and also made the setting of the green LED a function.

The main loop of the program prompts the user to input a command. If they type 'quit', the loop exits. If they type 'green' the LED will change state. The current state is held in the variable green_led.

There's an important difference in the input() function between Python2 and Python3. In Python2 it's best to use raw_input(), and not use input(). One you do have some user input, you need to clean it up to make checking easier. In the code below, the user_input is first trimmed of spaces with .strip(), and then all the letters are made lower-case with lower(), meaning something like "AbCDe" becomes "abcde". This allows us to check whether " GReen" equals "green" easily, and not have check a bunch of different letter-case combinations.

import RPi.GPIO as GPIO
import time

# Pin constants
PIN_GREEN  = 17
PIN_OTHER1 = 21
PIN_OTHER2 = 26

def setupGPIO():
    # Configure GPIO PINs
    GPIO.setwarnings( False )
    GPIO.setmode( GPIO.BCM )
    GPIO.setup( PIN_OTHER1, GPIO.OUT )
    GPIO.setup( PIN_OTHER2, GPIO.OUT )
    GPIO.setup( PIN_GREEN,  GPIO.OUT )

def setGreenPin( status ):
    """ Turn the Green-LED's PIN High or Low """
    if ( status == True ):
        GPIO.output( PIN_GREEN, True )
    else:
        GPIO.output( PIN_GREEN, False )

### Main Loop

# Set the initial state
setupGPIO()
setGreenPin( False )  # start with the LED off

done      = False
green_led = False

# Loop around, reading user commands until they enter 'quit'
while not done:
    user_input = raw_input( "Colour> " )       # get input form the user
    # user_input = input( "Colour> " )         -- python3
    user_input = user_input.strip().lower()    # trim spaces, make all lower-case
    # What did the user say?
    if ( user_input == 'quit' ):               # Is the user quitting?
        done = True            
    elif ( user_input == 'green' ):
        green_led = not green_led              # flip On <-> Off, and vice-versa
        setGreenPin( green_led )
Kingsley
  • 14,398
  • 5
  • 31
  • 53