首页 > 解决方案 > 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()

标签: pythonpython-3.x

解决方案


您是否考虑过设置某种计时器,一旦按下按钮就会关闭?然后,这将触发一个循环,该循环将检查给定时间是否再次按下按钮。如果时间已过,则循环结束并执行一条指令,如果按钮已复位,则程序执行另一条指令。

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

推荐阅读