MicroPython+Raspberry Pi Pico按键多次触发问题及单次执行方案
解决Raspberry Pi Pico按键按下多次触发代码的问题
你遇到的问题核心是机械按键的抖动效应:按下或松开按键时,金属触点会短暂弹跳,导致引脚电平反复波动,触发多次中断,所以你的my_handler会被重复调用。另外,中断处理函数里用utime.sleep(1)会阻塞系统,还可能加剧触发异常。下面是几种可行的解决方法:
1. 修正触发边沿(先确认接线匹配)
如果你的按键是一端接3.3V、一端接引脚,搭配Pin.PULL_DOWN的话:
- 未按下时引脚为低电平,按下时变为高电平,按下动作对应的是IRQ_RISING边沿,而非IRQ_FALLING。如果用反了边沿,会在松开按键时触发,加上抖动就会多次执行。
修正后的中断触发配置:
button.irq(trigger=machine.Pin.IRQ_RISING, handler=my_handler)
2. 软件消抖(中断方式)
在中断处理中加入时间判断,过滤掉抖动带来的重复触发:
from machine import Pin import utime button = Pin(3, Pin.IN, Pin.PULL_DOWN) last_trigger_time = 0 DEBOUNCE_DELAY = 200 # 消抖时间,可根据按键调整(一般100-300ms) def my_handler(button): global last_trigger_time current_time = utime.ticks_ms() # 只有两次触发间隔超过消抖时间,才执行代码 if utime.ticks_diff(current_time, last_trigger_time) > DEBOUNCE_DELAY: print("hello") last_trigger_time = current_time button.irq(trigger=machine.Pin.IRQ_RISING, handler=my_handler)
3. 主循环轮询消抖(非中断方式)
如果不需要用中断,也可以在主循环里定期检查按键状态,避免抖动干扰:
from machine import Pin import utime button = Pin(3, Pin.IN, Pin.PULL_DOWN) last_button_state = False last_check_time = 0 DEBOUNCE_DELAY = 200 while True: current_time = utime.ticks_ms() if utime.ticks_diff(current_time, last_check_time) > DEBOUNCE_DELAY: current_state = button.value() # 仅当按键状态稳定变化时执行动作 if current_state != last_button_state: last_button_state = current_state if current_state == 1: # 按键按下(PULL_DOWN配置下,按下时电平为高) print("hello") last_check_time = current_time
注意:中断处理函数里尽量不要使用utime.sleep()这类阻塞函数,会占用系统资源,影响其他任务的执行。
内容的提问来源于stack exchange,提问作者JulianJ
相关产品推荐
相关产品推荐

