RPI Pico MicroPython:如何判断触发中断的引脚?
解决RPI Pico中断函数识别触发引脚的问题
不用解析字符串,有两种简单可靠的方法:
方法一:访问Pin对象的pin属性
MicroPython的RP2 Pin对象自带pin属性,直接就能获取引脚的编号(比如14或15),修改你的代码如下:
from machine import Pin import time # 初始化全局变量 button_pressed_count = 0 button_debounce = False cf_button_status = 0 # 引脚定义 cf_close = Pin(14, Pin.IN, Pin.PULL_UP) cf_open = Pin(15, Pin.IN, Pin.PULL_UP) def button_isr(pin): global button_pressed_count, button_debounce, cf_button_status time.sleep_ms(1) # 获取触发中断的引脚编号 trigger_pin = pin.pin print("触发中断的引脚: GPIO{}".format(trigger_pin)) if not button_debounce: print("进入防抖逻辑") button_pressed_count += 1 button_debounce = True # 可根据引脚编号区分处理逻辑 if trigger_pin == 14: cf_button_status = 1 # 对应cf_close引脚 elif trigger_pin == 15: cf_button_status = 2 # 对应cf_open引脚 # 绑定中断 cf_close.irq(trigger=Pin.IRQ_FALLING, handler=button_isr) cf_open.irq(trigger=Pin.IRQ_FALLING, handler=button_isr)
方法二:通过lambda传递自定义标识
如果担心不同MicroPython版本的属性兼容性,还可以在绑定中断时,用lambda给处理函数传递自定义的引脚标识,代码示例:
from machine import Pin import time button_pressed_count = 0 button_debounce = False cf_button_status = 0 cf_close = Pin(14, Pin.IN, Pin.PULL_UP) cf_open = Pin(15, Pin.IN, Pin.PULL_UP) def button_isr(pin, pin_tag): global button_pressed_count, button_debounce, cf_button_status time.sleep_ms(1) print("触发中断的引脚标识: {}".format(pin_tag)) if not button_debounce: print("进入防抖逻辑") button_pressed_count += 1 button_debounce = True cf_button_status = pin_tag # 绑定中断时传递自定义标识 cf_close.irq(trigger=Pin.IRQ_FALLING, handler=lambda pin: button_isr(pin, "close")) cf_open.irq(trigger=Pin.IRQ_FALLING, handler=lambda pin: button_isr(pin, "open"))
注意:用
time.sleep_ms(1)做防抖不够严谨,容易阻塞中断处理,建议改用时间戳对比的方式实现防抖。
内容的提问来源于stack exchange,提问作者Adrian
相关产品推荐
相关产品推荐

