中断(interrupt)停止Arduino的当前工作,以便可以完成一些其他工作。

假设你坐在家里和别人聊天。突然电话响了。停止聊天,拿起电话与来电者通话。当你完成电话交谈后,你回去和电话响之前的那个人聊天。

同样,你可以把主程序想象成是与某人聊天,电话铃声使你停止聊天。中断服务程序是在电话上通话的过程。当通话结束后,你回到你聊天的主程序。这个例子准确地解释了中断如何使处理器执行操作。

主程序在电路中运行并执行一些功能。但是,当发生中断时,主程序在另一个程序执行时停止。当这个程序结束时,处理器再次返回主程序。

重要特征

这里有一些关于中断的重要特征:

  • 中断可以来自各种来源。在这种情况下,我们使用的是由数字引脚上的状态改变触发的硬件中断。

  • 大多数Arduino设计有两个硬件中断(称为“interrupt0”和“interrupt1”)分别硬连接到数字I/O引脚2和3。

  • Arduino Mega有六个硬件中断,包括引脚21,20,19和18上的附加中断(“interrupt2”到“interrupt5”)。

  • 你可以使用称为“中断服务程序”(Interrupt Service Routine,通常称为ISR)的特殊函数来定义程序。

  • 你可以定义该程序并指定上升沿,下降沿或两者的条件。在这些特定条件下,将处理中断。

  • 每次在输入引脚上发生事件时,都可以自动执行该函数。

中断类型

有两种类型的中断:

  • 硬件中断 - 它们响应外部事件而发生,例如外部中断引脚变为高电平或低电平。

  • 软件中断 - 它们响应于在软件中发送的指令而发生。“Arduino语言”支持的唯一类型的中断是attachInterrupt()函数。

在Arduino中使用中断

中断在Arduino程序中非常有用,因为它有助于解决时序问题。中断的良好应用是读取旋转编码器或观察用户输入。一般情况下,ISR应尽可能短且快。如果你的草图使用多个ISR,则一次只能运行一个。其他中断将在当前完成之后执行,其顺序取决于它们的优先级。

通常,全局变量用于在ISR和主程序之间传递数据。为了确保在ISR和主程序之间共享的变量正确更新,请将它们声明为volatile。

attachInterrupt语句语法

attachInterrupt(digitalPinToInterrupt(pin),ISR,mode);//recommended for arduino board
attachInterrupt(pin, ISR, mode) ; //recommended Arduino Due, Zero only
//argument pin: the pin number
//argument 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 an interrupt service routine.
//argument mode: defines when the interrupt should be triggered.

以下三个常量被预定义为有效值:

  • LOW :在引脚为低电平时触发中断。

  • CHANGE :在引脚更改值时触发中断。

  • FALLING :当引脚从高电平变为低电平时触发中断。  

示例

int pin = 2; //define interrupt pin to 2
volatile int state = LOW; // To make sure variables shared between an ISR
//the main program are updated correctly,declare them as volatile.

void setup() {
   pinMode(13, OUTPUT); //set pin 13 as output
   attachInterrupt(digitalPinToInterrupt(pin), blink, CHANGE);
   //interrupt at pin 2 blink ISR when pin to change the value
} 
void loop() { 
   digitalWrite(13, state); //pin 13 equal the state value
} 

void blink() { 
   //ISR function
   state = !state; //toggle the state when the interrupt occurs
}