python - 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.
解决方案
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
推荐阅读
- css - 指向css的html链接不显示样式
- android - Espresso 可以在没有意图启动活动的情况下工作吗?
- c++ - 我应该如何在主函数中初始化时间?
- c# - Helix Viewport 在断点处暂停时继续缩放
- javascript - 为什么我没有从 JS 客户端(作为 Chrome 扩展程序)收到任何东西?
- python - 如何修复所有模块的 pip install 错误?
- javascript - 在three.js中使用不同材料的多个立方体
- rust - 如何在 actix-web 中将不可变对象注入到服务代码中?
- ruby - Pry 使用过时的 Ruby 版本运行
- reactjs - 滑块状态的 React Redux 设置