With an Arduino (or any other CPU)
there are 2 basic ways to use interrupts
With Arduinos, the problem is that each type of processor has a slightly different way of implementing interrupts.
As a result, if you write it yourself the code will be faster but not as portable.
However, if you use the
the code will be slower, but completely portable.
- Research the topic and write your own code
- Use a library
Regardless of the method chosen,
variables modified in an interrupt routine must be defined as volatile.
| EnableInterrupt library
To get a solid background on Arduino interrupts, I suggest
this article by Nick Gammon
which is specific to the Arduino Uno (Atmega328).
The main differences between various Arduino processors are
With the Uno, all pins support a Pin Change interrupt, but, because they are ganged,
the hardware can not tell the program which pin changed - only that one of the pins in the block changed.
only 2 pins (D2 & D3) support individual interrupts and both
Rising Edge and Falling Edge detection.
(These 2 pins are referred to as external interrupts.)
- Which pins support Rising Edge and Falling Edge interrupts
- Whether an interrupt is attached to a single pin or a group of pins
hides the differences between various Arduino types and simulates
all the interrupt types on every pin - even when the hardware does not actually
support that type of interrupt.
Of course, there is a cost for this - the library is fairly complex
and the interrupt routines run much slower
(but probably still much faster than you need).
Assuming that you only want to enable interrupts on a few pins,
there is a mechanism
to reduce the amount of code generated.
Using this, you might save a few K of program space
and 42 bytes (2%) of your available static RAM (where data is stored).
This is the library I used to develop my
HC-SR04 Ultrasonic Sensor library.