首页 > 解决方案 > Controlling GPIO in RPI via python 2 input

问题描述

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.

标签: python

解决方案


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

推荐阅读