Hardware Reference
In-Depth Information
slowly from 0 to 255 and back again. Every time you press the button, the color
that is being faded immediately changes. This would not be possible using
polling because you would only be checking the button state after completing
a fade cycle; you would almost certainly miss the button press.
First, you need to understand volatile variables. Whenever a variable will be
changing within an interrupt, it must be declared as volatile . This is necessary
to ensure that the compiler handles the variable correctly. To declare a variable
as volatile, simply add volatile before the declaration:
volatile int selectedLED = 9;
To ensure that your Arduino is listening for an interrupt, you use attachIn-
terrupt() in setup() . The inputs to the function are the ID of the interrupt (or
the pin number for the Due), the function that should be run when an interrupt
occurs, and the triggering mode ( RISING , FALLING , and so on). In this program,
the button is connected to interrupt 0 (pin 2 on the Uno), it runs the swap()
function when triggered, and it triggers on the rising edge:
attachInterrupt(0, swap, RISING);
You need to write swap() and add it to your program; this is included in the
complete program code shown in Listing 12-1. That's all you have to do! After
you've attached the interrupt and written your interrupt function, you can write
the rest of your program to do whatever you want. Whenever the interrupt is
triggered, the rest of program pauses, the interrupt function runs, and then your
program resumes where it left off. Because interrupts pause your program, they
are generally very short and do not contain delays of any kind. In fact, delay()
does not even work inside of an interrupt-triggered function. Understanding
all of this, you can now write the following program to cycle through all the
LED colors and switch them based on your button press.
Listing 12-1: Hardware Interrupts for Multitasking—hw_multitask.ino
//Use Hardware-Debounced Switch to Control Interrupt
//Button pins
const int BUTTON_INT =0; //Interrupt 0 (pin 2 on the Uno)
const int RED =11; //Red LED on pin 11
const int GREEN =10; //Green LED on pin 10
const int BLUE =9; //Blue LED on pin 9
Search WWH ::




Custom Search