//uncomment this line if using a Common Anode LED
//#define COMMON_ANODE
// constants won't change. They're used here to set pin numbers:
const int buttonPin = 21; // the number of the pushbutton pin
const int redPin = 19;
const int greenPin = 18;
const int bluePin = 5;
enum color {
RED,
GREEN,
BLUE
};
color ledColor = RED;
int ledState = HIGH; // the current state of the output pin
int buttonState; // the current reading from the input pin
int lastButtonState = LOW; // the previous reading from the input pin
// the following variables are unsigned longs because the time, measured in
// milliseconds, will quickly become a bigger number than can be stored in an int.
unsigned long lastDebounceTime = 0; // the last time the output pin was toggled
unsigned long debounceDelay = 50; // the debounce time; increase if the output flickers
void setup() {
pinMode(buttonPin, INPUT);
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
// set initial LED state
setColor(255, 0, 0); // red
}
void loop() {
int reading = digitalRead(buttonPin);
if (reading != lastButtonState) {
// reset the debouncing timer
lastDebounceTime = millis();
}
if ((millis() - lastDebounceTime) > debounceDelay) {
if (reading != buttonState) {
buttonState = reading;
if (buttonState == HIGH) {
switch(ledColor) {
case RED:
ledColor = GREEN;
break;
case GREEN:
ledColor = BLUE;
break;
case BLUE:
ledColor = RED;
break;
}
}
}
}
// set the LED color
switch(ledColor) {
case RED:
setColor(255, 0, 0); // red
break;
case GREEN:
setColor(0, 255, 0); // green
break;
case BLUE:
setColor(0, 0, 255); // blue
break;
}
// save the reading. Next time through the loop, it'll be the lastButtonState:
lastButtonState = reading;
}
void setColor(int red, int green, int blue)
{
#ifdef COMMON_ANODE
red = 255 - red;
green = 255 - green;
blue = 255 - blue;
#endif
analogWrite(redPin, red);
analogWrite(greenPin, green);
analogWrite(bluePin, blue);
}