Arduino 编程相关 中断实验


中断是什么?


就是程序运行过程中,打断,执行打断的东西,然后继续运行原来的程序


例如


主程序 做作业

{

        不断做作业(循环)

       {

                 正在做。。。。

                 当(肚子饿)

          }

}


肚子饿了

{

          吃饭

}


实验效果

当我按下按键,改变了PIN 2的电平,触发中断,执行中断的程序



BOM表

Arduino Uno *1

按键       *1

跳线若干


接线




程序

官方提供的程序

const byte ledPin = 13;  //定义LED PIN为 IO 13,即板载的LED灯 
const byte interruptPin = 2;   //定义 用于中断的PIN 为 IO 2
volatile byte state = LOW;    //设置默认状态为LOW 意思指灯上电的时候是熄灭状态

void setup() {
  pinMode(ledPin, OUTPUT);        //设置ledPin 为输出状态
  pinMode(interruptPin, INPUT_PULLUP);  //设置interruptPin 为输入模式并且拉高
  attachInterrupt(digitalPinToInterrupt(interruptPin), blink, CHANGE);   //用attachInterrupt设置触发中断的指令
}

void loop() {   // 在程序不断循环当中,只要IO 2的电平发生改变就会触发中断的程序
  digitalWrite(ledPin, state);
}

void blink() {   //中断时执行的的程序
  state = !state;   // 反转当前状态
}




程序实现思路讲解

主要在void setup{}  程序里 使用attachInterrupt()函数添加中断设置

attachInterrupt(digitalPinToInterrupt(interruptPin), blink, CHANGE); 
//                             pin                    ISR    MODE
// 设置                        pin 2 为触发引脚      blink为中断时执行的程序     模式为CHANGE 当引脚电平发生改变时触发


Syntax 句法
attachInterrupt(digitalPinToInterrupt(pin), ISR, mode); 本例子使用的句法(recommended)推荐本句法使用
attachInterrupt(interrupt, ISR, mode);(not recommended) 不推荐
attachInterrupt(pin, ISR, mode) ;   (not recommended Arduino Due, Zero,MKR1000, 101 only)  不推荐

Parameters
interrupt: 中断 the number of the interrupt (int)
pin: 引脚 the pin number(Arduino Due, Zero, MKR1000 only)
ISR:  调用的函数 the ISR to call when the interrupt occurs; this function must take no parameters and return nothing. This function is sometimes referred to as aninterrupt service routine.
mode:  中断模式

defines when the interrupt should be triggered. Four constants are predefined as valid values:

  • LOW to trigger the interrupt whenever the pin is low,
  • 当针脚输入为低时,触发中断
  • CHANGE to trigger the interrupt whenever the pin changes value
  • 当针脚输入发生改变时,触发中断
  • RISING to trigger when the pin goes from low to high,
  • 当针脚输入由低变高时,触发中断
  • FALLING for when the pin goes from high to low.
  • 当针脚输入由高变低时,触发中断
 

The Due board allows also:

 
  • HIGH to trigger the interrupt whenever the pin is high.
  • 当针脚输入为高时,触发中断
(Arduino Due, Zero, MKR1000 only)
仅Due, Zero, MKR1000  适用

 还有中断的其他函数

digitalPinToInterrupt()

Interrupt() 可以被中断的代码

noInterrupt() 不可以被中断的代码

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值