Hardware Reference
In-Depth Information
//Volatile variables can change inside interrupts
volatile int selectedLED = RED;
void setup()
{
pinMode (RED, OUTPUT);
pinMode (GREEN, OUTPUT);
pinMode (BLUE, OUTPUT);
//The pin is inverted, so we want to look at the rising edge
attachInterrupt(BUTTON_INT, swap, RISING);
}
void swap()
{
//Turn off the current LED
analogWrite(selectedLED, 0);
//Then, choose a new one.
if (selectedLED == GREEN)
selectedLED = RED;
else if (selectedLED == RED)
selectedLED = BLUE;
else if (selectedLED == BLUE)
selectedLED = GREEN;
}
void loop()
{
for (int i = 0; i<256; i++)
{
analogWrite(selectedLED, i);
delay(10);
}
for (int i = 255; i>= 0; i--)
{
analogWrite(selectedLED, i);
delay(10);
}
}
When you load this up, your RGB LED should start fading back and forth on
one color. Every time you press the button, a new color will take over, with the
same brightness as the previous color.
NOTE YoucanwatchademovideooftheHardwareInterruptedArduinowith
buttondebouncingat www.exploringarduino.com/content/ch12 .Youcan
alsofindthisvideoontheWileywebsiteshownatthebeginningofthischapter.
Search WWH ::




Custom Search