python - 如何制作一个函数来检查按钮是否被按了一次或两次?

问题描述 投票:0回答:1

我想用Python为学校做一个任务。但问题是我不明白下面的函数如何工作。我们想做一个带灯和继电器的智能家居(现在我们用的是LED) 如果我们按一次按钮,灯就会亮,如果我们在1.5秒内按两次:所有的灯都会亮,以此类推......而且我们还必须在灯已经亮的时候做一个功能......。

所以我的问题是 "我如何告诉或让python知道我按了一次、两次或更多的按钮,或者按住它,让它做一个函数?"

这是我的代码(我们的工作是在空中上传到树莓皮上)

#!/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()
python python-3.x
1个回答
0
投票

你有没有想过设置一些定时器,一旦按钮被按下就会关闭?这样就会触发一个循环,在给定的时间内检查是否再次按下按钮。如果时间已过,循环结束,并执行一条指令,如果按钮已被复位,程序将执行另一条指令。

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
© www.soinside.com 2019 - 2024. All rights reserved.