python - python - 如何创建一个函数来检查按钮是否按下一次或两次?
问题描述
我正在尝试用 Python 为学校做一个任务。但问题是我不明白以下功能是如何工作的:所以我们正在尝试制作一个带有灯和继电器的智能家居(现在我们使用 LED)。如果我们按下按钮一次,灯就会亮,如果我们在 1.5 秒内按下两次:所有灯都会亮,依此类推......此外,我们必须在灯已经亮的时候做一个函数......
所以我的问题是“我如何告诉或让 python 知道我按下按钮一次或两次或更多次或按住它以使其发挥作用?”
这是我的代码(我们在空中上传到 Raspberry Pi
#!/usr/bin/env
__author__ = "Zino Henderickx"
__version__ = "1.0"
# LIBRARIES
from gpiozero import LED
from gpiozero import Button
from gpiozero.pins.pigpio import PiGPIOFactory
import time
IP = PiGPIOFactory('192.168.0.207')
# LED's
LED1 = LED(17, pin_factory=IP)
LED2 = LED(27, pin_factory=IP)
LED3 = LED(22, pin_factory=IP)
LED4 = LED(10, pin_factory=IP)
# BUTTONS
BUTTON1 = Button(5, pin_factory=IP)
BUTTON2 = Button(6, pin_factory=IP)
BUTTON3 = Button(13, pin_factory=IP)
BUTTON4 = Button(19, pin_factory=IP)
# LISTS
led [10, 17, 22, 27]
button [5, 6, 13, 19]
def button_1():
if BUTTON1.value == 1:
LED1.on()
time.sleep(0.50)
if BUTTON1.value == 0:
LED1.on()
time.sleep(0.50)
def button_2():
if BUTTON2.value == 1:
LED2.on()
time.sleep(0.50)
if BUTTON2.value == 0:
LED2.on()
time.sleep(0.50)
def button_3():
if BUTTON3.value == 1:
LED3.on()
time.sleep(0.50)
if BUTTON3.value == 0:
LED3.on()
time.sleep(0.50)
def button_4():
if BUTTON4.value == 1:
LED4.on()
time.sleep(0.50)
if BUTTON4.value == 0:
LED4.on()
time.sleep(0.50)
def check_button():
while True:
for i in range(BUTTON1):
toggle_button(i)
def main():
set_up_led()
set_up_button()
check_button()
# MAIN START PROGRAM
if __name__ == "__main__":
main()
解决方案
您是否考虑过设置某种计时器,一旦按下按钮就会关闭?然后,这将触发一个循环,该循环将检查给定时间是否再次按下按钮。如果时间已过,则循环结束并执行一条指令,如果按钮已复位,则程序执行另一条指令。
import time
#define max_time to consider a double execution
max_time = 1
while 1:
time.sleep(0.001) # do not use all the cpu power
# make a loop to test for the button being pressed
if button == pressed:
when_pressed = time.time()
while time.time() - when_pressed < max_time:
time.sleep(0.001) # do not use all the cpu power
if button == pressed:
# Instructions 2
#Instructions 1
推荐阅读
- python - 如何旋转绘图或图例 matplotlib (geopandas)
- azure - 是否有任何 REST API 或对 Azure 的调用可用于验证我的订阅 ID、客户端 ID、客户端密码和租户 ID 是否有效?
- c++ - C++ 中的加号运算符
- ubuntu - 在 ubuntu 20.04LTS 上安装 Rasa-x 时出现 ujson 错误
- sonarqube - SonarQube 质量门 - 行业默认值?
- javascript - 升级到 React Native 0.63.0 后 Pod 安装错误
- gitlab - 将修复推送到 GitLab 中已发布的分支
- javascript - 路径为“...”的多个字段设置为“initialValue”。无法决定选择哪一个,使用 react js
- c++ - 如何在覆盆子上链接 OpenCV 的正确目录?
- css - 防止 Edge 渲染表情符号