python - 如何在python中通过用户输入调用函数?
问题描述
我正在研究一个带电机的机械按钮按压器。我写了一些代码。我有一些任务要按不同的时间间隔按下按钮(例如长按、短按、3 秒按等)
from time import sleep
import RPi.GPIO as GPIO
DIR = 26 # Direction GPIO Pin
STEP = 19 # Step GPIO Pin
CW = 1 # Clockwise Rotation
CCW = 0 # Counterclockwise Rotation
SPR = 15 # Steps per Revolution (360 / 1.8)
GPIO.setmode(GPIO.BCM)
GPIO.setup(DIR, GPIO.OUT)
GPIO.setup(STEP, GPIO.OUT)
GPIO.output(DIR, CW)
MODE = (14, 15, 18) # Microstep Resolution GPIO Pins
GPIO.setup(MODE, GPIO.OUT)
RESOLUTION = {'Full': (0, 0, 0),
'Half': (1, 0, 0),
'1/4': (0, 1, 0),
'1/8': (1, 1, 0),
'1/16': (0, 0, 1),
'1/32': (1, 0, 1)}
GPIO.output(MODE, RESOLUTION['Full'])
step_count = SPR
delay = .0208
for x in range(step_count):
GPIO.output(DIR, CCW)
GPIO.output(STEP, GPIO.HIGH)
sleep(delay)
GPIO.output(STEP, GPIO.LOW)
sleep(delay)
sleep(2)
GPIO.output(DIR, CW)
for x in range(step_count):
GPIO.output(STEP, GPIO.HIGH)
sleep(delay)
GPIO.output(STEP, GPIO.LOW)
sleep(delay)
for x in range(step_count):
GPIO.output(DIR, CCW)
GPIO.output(STEP, GPIO.HIGH)
sleep(delay)
GPIO.output(STEP, GPIO.LOW)
sleep(delay)
sleep(8)
GPIO.output(DIR, CW)
for x in range(step_count):
GPIO.output(STEP, GPIO.HIGH)
sleep(delay)
GPIO.output(STEP, GPIO.LOW)
sleep(delay)
GPIO.cleanup()
在上面的代码中,您可以看到我有两个间隔,即按下 2 秒和按下 8 秒。所以我想要一些东西,当我们运行代码时,它会询问您要使用哪个函数,然后在给出输入后它将调用该特定间隔,并且该按钮将在该间隔内被按下。任何帮助将不胜感激。
解决方案
我不确定我是否正确理解了您想要请求用户输入的上下文(因为大多数 RP 都用于首先无法轻松获得命令提示符的环境)。
但是假设你确实有某种 shell 来运行这个 Python 脚本,这是一种方法:
def short_press():
...
def long_press():
...
actions = {'short': short_press, 'long': long_press}
command = input('Choose an action: ({})'.format(', '.join(actions.keys())))
if command in actions:
actions[command]()
else:
raise ValueError('{} is not a recognized action'.format(command)
推荐阅读
- sql - 如何提高 XMLAGG(XMLELEMENT() 编写的查询性能?
- javascript - React 子组件没有呈现在它应该呈现的位置
- .net - DAO.DBEngine.CompactDatabase 的 ODBC 等效项
- c# - 从 UDP 接收到的消息播放音频,点击声音(Naudio API)
- r - 如何将带有“,”的“价格”列整理为数字格式?例如 1,250,000 到 1250000(R 编程)
- database - 我创建了一个 laravel 然后
- java - 单击选项卡时,我想显示两个片段
- powershell - 审核远程服务器上的本地用户帐户
- oracle - 您如何分析触发器在 OracleDB 中需要多长时间?
- python - 从输入中找到平均值