In this activity your will learn two ways to control and output LED with an input Button. At this point you should know how to control LED outputs with the Arduino, and how to read input data from a button and output that data to the serial monitor.
The button example program uses an IF statement to set the LED to on or off. The if statement has two basic parts the condition or test contained inthe brackets just after the keyword if. The condition is comparison ot test equation if it is true or correct then the computer will complete the code contained in the braces {} that follow the if. If the test in not true the program skips the content of the braces and jumps to the next code line. The Else statment allows your if statement to do one thing if the test is true and another if it is false.
Build the Button circuit according to the Arduino Website load the button program from the Ardunio Examples in the Arduino software. Run the program to see it work.
delete the else statement and the realted text.
else {
// turn LED off:
digitalWrite(ledPin, LOW);
}
Upload the program again and see how the if statement works without the else.
Controling the LED wiht an assignment Statement.
Starting with the button program add the following line to create a variable for LEDstate.
int LEDstate=0;
add the line near the begining of the program with buttonState.
Delete the if and else statements.
if (buttonState == HIGH) {
// turn LED on:
digitalWrite(ledPin, HIGH);
}
else {
// turn LED off:
digitalWrite(ledPin, LOW);
}
An assignment statement is a simple statement that make one variable equal to another variable or equation. Add the following assignment statement to make the LED state equal to the Button State
LEDstate=buttonState; // add this line after this line buttonState = digitalRead(buttonPin);
Add an digital write statement to give the updated output, add this line just befor the final brace }
digitalWrite(ledPin, LEDstate);
upload and run the sketch to the arduino.
Questions:
What is the effect of deleting the Else statement?
When would you use an if statement instead of an assingment statement?