Sunday, July 31, 2016

Article #20 : Using interrupts with Arduino Uno

Introduction :

An interruption, as its name indicates, interrupts momentarily the program executed by Arduino to perform another task. When the task finishes, the program takes on the lead from the axact place where it was interrupted.

Interruptions could be ideally used for listening to user’s actions, for example pressing a button, a keypad, or the changing state of a sensor without the need of constantly reading a pin’s state.

How does it work ?

Arduino Uno (ATMega328) can manage 2 external interruptions on its pins INT0 and INT1 mapped to pins D2 and D3 on the microcontroller board.
Interruptions could be triggered under 4 modes :

  •             LOW : The pin is in a low state
  •             RISING : The pin passes from low to high state
  •             FALLING : The pin passes from high to low state
  •             CHANGE : The pin has changed state

Creating an interrupt :

To “listen” for an interruption on Arduino, you only have to attach an interrupt on either pin D2 or D3 using the method attachInterrupt. This method takes as an argument the interruption’s pin number 0 or 1, the name of the function called by the interruption, and finally the interruption mode as the following example shows :


attachInterrupt(0, myInterrupt(), RISING);

Even though Arduino’s pin is D2, we indicate 0 for the interruption’s pin (0 for INT0 / D2, 1 for INT1 / D3).
The function attached to the interrupt have to take a small amout of time to execute and it is also forbidden to use time based instructions in the interior of the function as it blocks the microcontroller.

Application :

In the following application, we attach an interruption to a push button. The program writes the interruption number to the serial monitor every time the button is pushed.

Code :


int interruption = 0; //interrupt 0 is on digital pin 2
volatile int numInterrupt = 0; //variables used inside interrupt     functions declared as volatile

void setup() {

       Serial.begin(9600);
       attachInterrupt(interruption, functionInterruption, FALLING);

}

Void loop() {

//simulating a task being executed repeatedly
            While(true) {
                        Serial.print(“.”);
                        delay(250);

}
}

Void functionInterruption() {

            Serial.print(“Interrupt numero ”);
            Serial.println(numInterrupt);
            numInterrupt++;


}