【MicroPython ESP32】外部中断使用示例

【MicroPython ESP32】外部中断使用示例


  • ✨本案例基于Thonny平台开发。✨

📌ESP32外部中断相关函数在machine模块中

-🌿 通过Thonny平台,Shell调试窗口查询相关函数:

>>> import machine
>>> help(machine)
📖中断相关函数
  • 📑state = machine.disable_irq(): 禁用中断
  • 📑machine.enable_irq(state):启用中断

⛳中断触发回调示例

import machine
import time

led=machine.Pin(2,machine.Pin.OUT)
sw= machine.Pin(0,machine.Pin.IN)
def blink(num,t_on,t_off,msg):
    counter =0
    while (counter <num):        
        led.on()
        time.sleep(t_on)
        led.off()
        counter +=1
        time.sleep(t_off)
        counter +=1
    print(msg)
    
def call_back(pin):# 中断回调函数,这里的形参默认为`pin`中断引脚,必须要有
    print(pin)# 中断引脚
    print(int(str(pin)[4:-1]))# 提取中断引脚号
    blink(6,0.5,0.6,'hello world')
    
 # 上升沿或下降沿中断   
sw.irq(trigger=machine.Pin.IRQ_FALLING | machine.Pin.IRQ_RISING,handler =call_back)
🎆为防止中断来时重复执行相关业务代码,可以将想要执行的业务代码放到主函数当中,中断回调函数当中只设定标志位。在Micropython当中,在执行回调函数时关闭中断,然后执行完毕后再开启中断,如果回调函数中要执行的业务代码时间比较长,在此过程中,容易触发看门狗中断,从而导致重启,所以只能将代码放到主函数当中来执行。
  • 🧾示例代码
import machine
import time
from machine import WDT

led=machine.Pin(2,machine.Pin.OUT)
sw= machine.Pin(12,machine.Pin.IN)
Tri = 0
def blink(num,t_on,t_off,msg):
    counter =0
    while (counter <num):        
        led.on()
        time.sleep(t_on)
        led.off()
        counter +=1
        time.sleep(t_off)
        counter +=1
    print(msg)
def call_back(pin):
    global Tri
    print(pin)
#     state = machine.disable_irq()#禁用
    print(int(str(pin)[4:-1]))
    Tri =  1
#     machine.enable_irq(state)
    
sw.irq(trigger=machine.Pin.IRQ_FALLING | machine.Pin.IRQ_RISING,handler =call_back)# 上升沿或和下降沿都可以触发中断

        
# if __name__=='__main__':
while 1:
    if(Tri ==1):        
        blink(6,0.5,0.6,'hello world')
        Tri =0
    else:
        led.off()
    

在这里插入图片描述

🎄中断计数器示例
import machine
interruptCounter = 0#与主程序通信
totalInterruptsCounter = 0#计算中断事件次数
def callback(pin):#定义回调函数    
    global interruptCounter#声明为全局变量
    interruptCounter = interruptCounter+1
    
p12 = machine.Pin(12, machine.Pin.IN, machine.Pin.PULL_UP)#引脚编号、引脚模式下降沿以及是否存在相关拉电阻
p12.irq(trigger=machine.Pin.IRQ_FALLING, handler=callback)#触发中断,回调模式
while True:
  if interruptCounter>0:
    state = machine.disable_irq()#禁用计数器
    interruptCounter = interruptCounter-1
    machine.enable_irq(state)#重新启动计数器
    totalInterruptsCounter = totalInterruptsCounter+1
    print("Interrupt has occurred: " + str(totalInterruptsCounter))

在这里插入图片描述

  • 3
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值