For your code to use a single input to affect multiple outputs, you need to use a variable between them to ‘hold’ the value. In this code, the button press affects the variable pressCount, then the pressCount affects the state of the LED light.


/* * Use a button to cycle through three LEDs or a multi-color LED. * Hold down the button to strobe! */ int pressCount = 0; //How many times the button has been pressed. void setup(){ pinMode(9, OUTPUT); //Set up your LED pins as outputs pinMode(10, OUTPUT); pinMode(11, OUTPUT); pinMode(A5,INPUT_PULLUP); //button } void loop(){ //If the button is pressed, increase the counter variable by 1 if(digitalRead(A5)==LOW){ pressCount++; //Delay before next button press is sensed. Lower delay = faster strobe delay(250); } //Use the pressCount to determine which light is on. if(pressCount==1){ digitalWrite(10, LOW); //turn off the light on pin 10 and... digitalWrite(11, HIGH); //turn on the light on pin 11 } else if(pressCount==2){ digitalWrite(11, LOW); digitalWrite(9, HIGH); } else if(pressCount==3){ digitalWrite(9, LOW); digitalWrite(10, HIGH); //No matter how many LEDs you add, the last "if" sets pressCount to 0 pressCount=0; } } // (c) 2017 Let's Start Coding. License:


How many can you complete? Change the code and hardware according to the challenges below. Upload your code to see the effect when you're finished. Complete a challenge? Check it off the list!


Read the Code Walkthrough Text (click to open)


New Concept: Combining if and else-if Statements

You can combine if and else-if statements to define a wide number of 'paths' for a program to take. Each else-if is another decision for the code to make. You can also use else-if statements to prioritize decisions. Think of deciding where to eat as you walk down a street. You may think "If pizza is available, I'll have that. If not, I'll look for Greek. If that's not available, I'll look for Chinese food.". This set of decisions prioritizes pizza over Greek and Greek over Chinese. 

Now imagine the same decision using only if statements. Your decision would be "If pizza is available, I'll have that. If Greek is available, I'll have that. If Chinese is available, I'll have that." You would be extremely full!


If you're having trouble, try to run a program that can help you find the answer.

1. What is the maximum number of "else if" statements you can string together?

2. When does an 'else if' statement get run?