Skip to main content
 首页 » 编程设计

python之如何根据 Python 中按下的时间使按钮按下有不同的输出

2025年05月04日9yxwkf

我正在尝试学习如何编程。我正在为我的 Raspberry Pi 制作这个脚本,但这个概念不必专门针对它。我想要按下按钮来执行两个命令之一:

如果按住一秒钟,则运行命令 A 如果按住五秒钟,则运行命令 B 在等待B注册的过程中,命令A运行多次是可以的。

这是我的脚本,之后我会解释它的用途:

import RPi.GPIO as GPIO 
import uinput 
inport time 
import os 
 
GPIO.setmode(GPIO.BCM) 
GPIO.setup(17, GPIO.IN) 
 
def main(): 
     events = ( 
          uinput.KEY_ESC, 
          ) 
 
     device = uinput.Device(events) 
 
     device.emit(uinput.KEY_ESC, 1) #Press 
     device.emit(uinput.KEY_ESC, 0) #Release 

然后,这是我想添加的两件事:

while 1: 
 
     if time.sleep(1) 
     if GPIO.input(17)==True: 
          main() 
          break 
 
while 1: 
 
     if time.sleep(10) 
     if GPIO.input(17)==True: 
          os.system("sudo reboot") 
          break 

基本上,此脚本将使按钮有两个用途。按下它一秒钟将模拟 ESC 键的击键。按住它十秒钟将导致它重新启动系统。我怎样才能让这两者同时发生?学习 Python 对我来说非常具有挑战性,但直到现在我还没有任何编程经验。

请您参考如下方法:

虽然我没有使用 Raspberry Pi 的经验,但我决定回答你,因为看起来你一直没有引起大师的注意。与本文对应Buttons and Switches ,我认为下面的代码应该可以正常工作:

import os 
import time 
while True: 
    if GPIO.input(17): 
    #start counting pressed time 
    pressed_time=time.monotonic() 
    while GPIO.input(17): #call: is button still pressed 
        # just to force process wait 
        # may be possible use in this time.sleep(1) but I don't have confidence 
        pass 
    pressed_time=time.monotonic()-pressed_time 
    if pressed_time<5: 
        #send corresponding signal, you mentioned to call "main()", ok then: 
        main() 
    elif pressed_time>=5: 
        os.system("sudo reboot")