我正在试着用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()发布于 2020-05-03 22:08:54
你有没有想过设置一个只要按下按钮就会响的计时器?这将触发一个循环,该循环将在给定时间内检查按钮是否再次被按下。如果时间已过,则循环结束并执行一条指令,如果按钮已重置,则程序执行另一条指令。
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 1https://stackoverflow.com/questions/61575494
复制相似问题