📜  Arduino-中断

📅  最后修改于: 2020-11-05 03:36:40             🧑  作者: Mango


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

假设您坐在家里,和某人聊天。突然电话响了。您停止聊天,然后接电话与呼叫者通话。完成电话交谈后,您可以在电话铃响之前返回与该人聊天。

同样,您可以将主要例程视为与某人聊天,电话响铃会导致您停止聊天。中断服务程序是电话交谈的过程。电话交谈结束后,您可以返回到聊天的主要例程。该示例准确地解释了中断如何导致处理器动作。

主程序正在运行并在电路中执行某些函数。但是,当发生中断时,主程序将暂停,同时执行另一个例程。该例程完成后,处理器将再次返回主例程。

打断

重要功能

这是有关中断的一些重要功能-

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

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

  • Arduino Mega具有六个硬件中断,包括在插针21、20、19和18上的附加中断(“ interrupt2”至“ interrupt5”)。

  • 您可以使用称为“中断服务例程”的特殊函数(通常称为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.

以下三个常量已预定义为有效值-

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

  • 更改以在引脚改变值时触发中断。

  • 每当引脚从高电平变为低电平时都会掉落

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
}