Project 1.05 wait to blink
Now we’ll expand Project 1.01 to include user input. Upload this sketch to your Arno, and wait, and wait, and … nothing happens. Not until you press SW1.
Concepts: conditional statement, while loop, digitalRead
Circuits:
Concepts: conditional statement, while loop, digitalRead
Circuits:
Since we’re going to use SW1 we declare the variable with the correct pin number at the beginning of the sketch:
int SW1 = 1;
We also declare an int variable to hold the value we read from SW1 We give it an initial value of HIGH:
int isPress = HIGH;
In the setup() block we set the pinMode of LED1 to OUTPUT as we’ve done before. We need to use SW1 as an INPUT so we set it using pinMode:
pinMode(LED1,OUTPUT);
pinMode(SW1,INPUT);
Now we encounter our first while loop. Since we initially set isPress to HIGH, our conditional statement is true and we enter the loop:
while(isPress == HIGH){
We want to stay in this loop until SW1 is pressed. This is going to hold up our sketch. Nothing will blink or do anything else until we press SW1. If you look back at Circuit 2, the pull-up resistor holds the SW1 pin in a HIGH state until the button is pressed. By pressing SW1 we create a path from our microcontroller pin to ground. This will quickly pull the voltage on the pin to LOW. Within the loop, we keep checking on the status of SW1 using a digitalRead statement. We store the resulting value in isPress:
// keep checking button
isPress = digitalRead(SW1);
}
Once isPress is LOW, the conditional statement is no longer true and we break out of the loop. We’ll then enter the loop() block and blink the LED, just as we did in Project 1.01.
int SW1 = 1;
We also declare an int variable to hold the value we read from SW1 We give it an initial value of HIGH:
int isPress = HIGH;
In the setup() block we set the pinMode of LED1 to OUTPUT as we’ve done before. We need to use SW1 as an INPUT so we set it using pinMode:
pinMode(LED1,OUTPUT);
pinMode(SW1,INPUT);
Now we encounter our first while loop. Since we initially set isPress to HIGH, our conditional statement is true and we enter the loop:
while(isPress == HIGH){
We want to stay in this loop until SW1 is pressed. This is going to hold up our sketch. Nothing will blink or do anything else until we press SW1. If you look back at Circuit 2, the pull-up resistor holds the SW1 pin in a HIGH state until the button is pressed. By pressing SW1 we create a path from our microcontroller pin to ground. This will quickly pull the voltage on the pin to LOW. Within the loop, we keep checking on the status of SW1 using a digitalRead statement. We store the resulting value in isPress:
// keep checking button
isPress = digitalRead(SW1);
}
Once isPress is LOW, the conditional statement is no longer true and we break out of the loop. We’ll then enter the loop() block and blink the LED, just as we did in Project 1.01.