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
}