Interrupts



On a very basic level, an interrupt is an signal that interrupts the current processor activity. It may be triggered by an external event (change in pin state) or an internal event (a timer or a software signal). Once triggered, an interrupt pauses the current activity and causes the program to execute a different function. This function is called an interrupt handler or an interrupt service routine (ISR). Once the function is completed, the program returns to what it was doing before the interrupt was triggered.

Interrupts are asynchronous events, that is, something that occurs outside of the regular flow of your program – it can happen at any time, no matter what your code is crunching on at the moment. This means that rather than manually checking whether your desired event has happened, you can let your AVR do the checking for you.

Two of the pins on the Arduino D2 and D3 can have interrupts attached to them. If these pins receive a signal in a special way, the Arduino's processor will suspend what it was doing and run the function attached to the interrupt.

The following program will detect when a pushbutton has been pressed, and perform an action based on that press. Here’s our example circuit:
interrupt_sample_circuit-e1320019512826.png
#include <avr/interrupt.h>
#define led ___
#define interruptPin 2
volatile int period=500;
                             //
void setup(){
    sei();                    // Enable global interrupts
    EIMSK |= (1 << INT0);     // Enable external interrupt INT0
   
	pinMode(led, OUTPUT);
    pinMode(interruptPin, INPUT);
    digitalWrite(interruptPin, HIGH);    // Enable pullup resistor
    
    //parameter one specifies which interrupt pin
    //parameter two specifies which function to call
    //parameter three is either LOW, CHANGE, FALLING or RISING
    attachInterrupt(0, goFast, FALLING);
}
void loop(){
  digitalWrite(led,HIGH);
  delay(period);
  digitalWrite(led,LOW);
  delay(period);
}
void goFast(){
    period=100;
}