【问题标题】:Trigger code just once each time a button is pressed?每次按下按钮时触发代码一次?
【发布时间】:2022-07-21 18:33:36
【问题描述】:

我正在试验 micropython 和 raspberry pico。我有一个按钮,由于某种原因,按下时会触发多次。如何让按钮每次按下时只执行一次代码?

from machine import Pin
import utime

button = Pin(3, Pin.IN, Pin.PULL_DOWN)

def my_handler(button):
  print("hello")
  utime.sleep(1)
  
button.irq(trigger = machine.Pin.IRQ_FALLING, handler = my_handler)

【问题讨论】:

    标签: micropython


    【解决方案1】:

    我在这里找到了一篇有用的文章解决了我的问题

    https://www.coderdojotc.org/micropython/advanced-labs/02-interrupt-handlers/

    通过测量按下按钮之间的时间,我可以多次停止代码触发。

    last_time = 0
    
    button = Pin(3, Pin.IN, Pin.PULL_DOWN)
    
    def my_handler(button):
        global last_time
        new_time = utime.ticks_ms()
        # if it has been more that 1/5 of a second since the last event, we have a new event
        if (new_time - last_time) > 400: 
            print("hello")
            last_time = new_time
    

    【讨论】:

      猜你喜欢
      • 2016-02-09
      • 1970-01-01
      • 2021-04-09
      • 2015-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-27
      相关资源
      最近更新 更多