|
| 1 | +/* |
| 2 | + Interrupt |
| 3 | + Use a pushbutton to control an LED; powered by interrupts. |
| 4 | +
|
| 5 | + This sample uses an interrupt service routine (ISR) named `blink` to toggle |
| 6 | + a global state variable and then uses the built-in LED to display the value |
| 7 | + of the cached state to the user. The work of updating the cached state happens |
| 8 | + asychronously in the interrupt service routine. |
| 9 | +
|
| 10 | + This sample can easily be modified from behaving as a button into behaving as |
| 11 | + a switch, by changing the interrupt mode from CHANGE to LOW. Futhermore, this |
| 12 | + example can be modified to update the built-in LED from inside in the ISR, |
| 13 | + which would allow the loop function to be empty yet still allow actions and |
| 14 | + reactions to occur. |
| 15 | +
|
| 16 | + This example code is in the public domain (adapted from |
| 17 | + https://www.arduino.cc/en/Reference/attachInterrupt). |
| 18 | +
|
| 19 | + adapted 1 APR 2017 |
| 20 | + by Zachary J. Fields |
| 21 | +*/ |
| 22 | + |
| 23 | +const byte interruptPin = 2; |
| 24 | +volatile byte state = LOW; |
| 25 | + |
| 26 | +void blink () { |
| 27 | + state = !state; // toggle the cached state |
| 28 | +} |
| 29 | + |
| 30 | +// the setup function runs once when you press reset or power the board |
| 31 | +void setup () { |
| 32 | + // initialize digital pin LED_BUILTIN as an output. |
| 33 | + pinMode(LED_BUILTIN, OUTPUT); |
| 34 | + // initialize digital pin as input with pull-up resistor (i.e. always HIGH, unless deliberately pulled LOW) |
| 35 | + pinMode(interruptPin, INPUT_PULLUP); |
| 36 | + // attach an interrupt service routine to be executed when pin state changes |
| 37 | + attachInterrupt(digitalPinToInterrupt(interruptPin), blink, CHANGE); |
| 38 | +} |
| 39 | + |
| 40 | +// the loop function runs over and over again forever |
| 41 | +void loop () { |
| 42 | + // update the LED to reflect the cached state updated with interrupts |
| 43 | + digitalWrite(LED_BUILTIN, state); |
| 44 | +} |
| 45 | + |
0 commit comments