//This arduino sketch blinks red one press, green the next, then blue the next
//With a second button, the sequence is reversed
//Note that in this software the RGB LED has a common "anode",
//meaning the common pin goes to positive rather than negative.
//In this case HIGH turns the LED off and LOW turns it on
//In your kits, the RGB LED is common "cathode", meaning
//the common pin goes to negative (GND pin).
//This is the same sketch as before, but we are going to use variables
//in order to make it more readable.
//Here we declare the variables:
int red = 5;
int green = 6;
int blue = 7;
int button_forward = 2;
int button_backward = 3;
//For this sketch, we are going to blink a different color every time
//the button is pressed. In order to do this, we need to store the number of
//the LED pin we want to blink next. We can do this with a variable!
int color_to_blink = 5; //We start at 5 because that's red
void setup() {
pinMode(red, OUTPUT); //Instead of using numbers to refer to the LED pins,
pinMode(green, OUTPUT); //We use the variables we just declared
pinMode(blue, OUTPUT);
digitalWrite(red, HIGH); //Turn the LEDs off to start with
digitalWrite(green, HIGH);
digitalWrite(blue, HIGH);
pinMode(button_forward, INPUT_PULLUP); //The button is attached to pin 2, so we set pin 2 as input
pinMode(button_backward, INPUT_PULLUP);
}
void loop() {
if(digitalRead(button_forward) == LOW) //If the button is pushed:
{
color_to_blink = color_to_blink + 1; //We are setting color_to_blink equal to itself plus 1
if(color_to_blink == 8) //If it equals 8, reset it to 5 for red
{
color_to_blink = 5; //This line sets color_to_blink to 5 for the red LED
}
digitalWrite(color_to_blink, LOW); //Turn current color LED on
delay(300); //Wait 300ms
digitalWrite(color_to_blink, HIGH); //Turn current color LED off
}
//Now we do the same thing but in reverse:
if(digitalRead(button_backward) == LOW) //If the button is pushed:
{
color_to_blink = color_to_blink - 1; //We are setting color_to_blink equal to itself minus 1
if(color_to_blink == 4) //If it equals 4, we have gone too low
{
color_to_blink = 7; //This line sets color_to_blink to 7 for the blue LED
}
digitalWrite(color_to_blink, LOW); //Turn current color LED on
delay(300); //Wait 300ms
digitalWrite(color_to_blink, HIGH); //Turn current color LED off
}
}