Arduino的中断函数格式为attachInterrupt(interrput,function,mode)。
attachInterrupt函数用于设置外部中断,有3个参数,interrput表示中断源编号(中断号)、function表示中断处理函数,mode表示触发模式,它们的具体含义如下
中断号:可选0或者1,在UNO板上分别对应2和3号数字引脚。在不同的Arduino型号上位置也不同,只有外部中断发生在以下端口,Arduino才能捕获到。以下是常见的几种型号板子的外部中断编号和对应引脚标号。
中断源编号 |
int.0 |
int.1 |
int.2 |
int.3 |
int.4 |
int.5 |
UNO\Ethernet |
2 |
3 |
|
|
|
|
Mega2560 |
2 |
3 |
21 |
20 |
19 |
18 |
Leonardo |
3 |
2 |
0 |
1 |
|
|
Due |
所有IO口均可 |
Due板的每个IO均可以进行外部中断,中断号即所使用的中断引脚编号。
中断处理函数:指定中断的处理函数,是一段子程序,当中断发生时执行该子程序,其中参数值为函数的指针。
触发模式:有下列几种类型
LOW 低电平触发
CHANGE 电平变化,高电平变低电平、低电平变高电平
RISING 上升沿触发
FALLING 下降沿触发
HIGH 高电平触发(该中断模式仅适用于Arduino due)
如果不需要使用外部中断了,可以用中断分离函数detachInterrupt(interrupt )来取消这一中断设置。
Example Code 用外部中断实现LED的亮灭切换
1 const byte ledPin = 13; //LED的引脚
2 const byte interruptPin = 2; //中断源引脚,根据所用板子查表得到中断编号interrupt
3 volatile byte state = LOW;
4
5 void setup()
6 {
7 pinMode(ledPin, OUTPUT);
8 pinMode(interruptPin, INPUT_PULLUP);
9 attachInterrupt(interrupt, blink, CHANGE);
10 }
11
12 void loop()
13 {
14 digitalWrite(ledPin, state);
15 }
16
17 void blink()
18 {
19 state = !state;
20 }