Arduino Lesson 4 – If Statements
The Magic of Buttons and LEDs
Understanding the Circuit
In order to comprehend how buttons and LEDs work in a circuit, let’s break it down. The button in question is connected to both the ground wire and the digital read wire, through a resistor between 1 and 10 K. When the button is pressed, it creates a bridge between the digital wire and the 5-volt line. The absence of a resistor between these two allows the digital wire to be pulled high. On the other hand, the LED is wired to ground on one side and to one of the digital pins on the Arduino (in this case, pin 8) on the other side.
Coding the Circuit
Now that we understand the circuitry, we can proceed to write the code. Our goal is to turn the LED on when we press the button. To achieve this, we will first set up the button and the LED at the beginning of our code by assigning them appropriate English names.
Implementing the Logic
After setting up the components, we can write the necessary code logic. We need to create conditions that will control the behavior of the LED based on the state of the button. If we use the digital write low function, the LED will turn off. Conversely, if we use the digital write high function, the LED will turn on.
The Final Result
By combining the physical circuit and the accompanying code, we can now achieve the desired result of turning the LED on and off by pressing the button. As we press the button, the circuit creates a connection between the digital wire and the 5-volt line, signaling the Arduino to turn the LED on. When the button is released, the circuit breaks, and the LED turns off.
Setting Up the English Name
In this tutorial, we will learn how to set up an English name for our code in order to make it more readable and easier to understand. Instead of referring to pin numbers directly, we can assign them English names.
Assigning English Names to Pins
To assign an English name to a pin, we simply declare a variable and give it a name. For example, if we want to assign a name to pin 7, we can write:
Int button = 7;
Now, whenever we need to refer to pin 7, we can use the variable name “button” instead. This makes our code more intuitive and easier to read.
Setting Up the LED
Next, let’s set up an LED on pin 8. To do this, we need to declare another variable and assign pin 8 to it:
Int LED = 8;
Now, we can easily refer to pin 8 as “LED” in our code.
Initializing Inputs and Outputs
In the void setup function, we need to initialize the inputs and outputs. Since the button is an input, we use the pinMode function with the “INPUT” mode:
PinMode(button, INPUT);
On the other hand, the LED is an output, so we use the pinMode function with the “OUTPUT” mode:
PinMode(LED, OUTPUT);
By setting up the inputs and outputs correctly, we ensure that our code can properly read signals from the button and send signals to the LED.
Using Conditional Statements
Now that we have set up the necessary variables and initialized the inputs and outputs, we can move on to the main part of our code – the void loop function. Here, we can start implementing our logic using conditional statements.
For example, if we want to execute a certain block of code only when a specific condition is met, we can use the “if” statement. It follows the format:
If (condition) {
// code to execute if condition is true
}
By using conditional statements, we can control the flow of our program and make it perform different actions based on certain conditions.
The If Statement: Conditional Execution
The if statement is a fundamental component of programming, allowing us to execute code based on a certain condition being true or false. By using the if statement, we can control the flow of our program and make decisions based on different scenarios. Let’s explore how it works and its application in a practical example.
Understanding the Syntax
The if statement is enclosed within a set of brackets, denoting the condition to be checked. If this condition evaluates to true, the code within the following curly brackets will be executed. If the condition is false, the code within the curly brackets will be bypassed.
Example: Using the If Statement to Control LED
Suppose we want to check if a button has been pressed, and if so, we want to turn on an LED. Otherwise, we want to keep the LED off. Let’s break down the code step by step.
Checking the Button’s Status
The first step is to determine the status of the button. We can do this using the digitalRead function, which returns either a high or low value. By writing digitalRead(button), we are checking the status of the button.
Creating the if Statement
Now that we have retrieved the button’s status, we can use an if statement to control the LED’s behavior. If the button has been pressed (evaluating to true), we will write the code to turn on the LED. In this case, we would write turnLEDOn(). If the button hasn’t been pressed (evaluating to false), we will write the code to turn off the LED. Here, we would write turnLEDOff().
The Importance of Comparisons in Coding
Coding is all about giving instructions to a computer and allowing it to make decisions based on certain conditions. One way to achieve this is through the use of if statements, which compare different values and execute specific actions based on the result. In this article, we will explore the significance of comparisons in coding, using a practical example.
The Role of if Statements
In order for a computer to make decisions, we need to provide it with something to compare against. This allows the computer to determine whether a certain condition is true or false. In our example, we are using a digital reader to check the status of a button. We are interested in knowing whether the button is being pressed or not.
Triggering the if Statement
Within our code, we have a specific condition that needs to be met in order for the if statement to be triggered. We want the if statement to be executed only when the button is pressed, or in other words, when the value of the button is equal to “high”. This comparison allows us to execute certain actions when the button is pressed, such as turning on an LED.
Executing Actions Based on the Comparison
Once the if statement is triggered, we can specify the actions that need to be executed. In our example, we want to turn on an LED. To do this, we use the “digitalWrite” function and specify the pin to which the LED is connected. In this case, we can either use the pin number directly (such as 8) or refer to a variable (such as LED) that holds the pin number. We also specify the value “high” to turn on the LED.
The Problem with the Current Code
While the current code allows us to turn on the LED when the button is pressed, it doesn’t include a way to turn off the LED. This means that once the LED is turned on, it will remain on indefinitely, even if the button is no longer being pressed. In order to address this issue, we need to add a digital write function with the value “low” within the void loop. This will ensure that the LED is turned off when the if condition is no longer met.
Comparisons play a crucial role in coding as they allow us to make decisions based on specific conditions. By using if statements and comparing values, we can execute different actions and create more dynamic and interactive programs. However, it’s important to ensure that our code includes all the necessary instructions to achieve the desired behavior.
The Power of the Else Statement in Programming
The else statement is a powerful tool in programming that allows us to create alternative actions based on a condition. It is closely connected to the if statement and can significantly enhance the functionality of our code. Let’s explore how the else statement works and its applications in programming.
Understanding the Else Statement
In simple terms, the else statement functions as a backup plan. It serves as a contingency when the conditions stated in the if statement are not met. By using the else statement, we can execute a specific set of instructions if the condition in the if statement evaluates to false.
Implementing the Else Statement in Arduino Programming
In Arduino programming, the else statement can be extremely useful, especially when dealing with input and output operations. Let’s consider a practical example.
Suppose we have a button connected to our Arduino board, and an LED connected to one of its digital pins. We want the LED to turn on when the button is pressed and turn off when the button is not pressed. This is where the else statement comes into play.
Code Example
Here is the code snippet to achieve this functionality:
“`arduino
Int buttonPin = 2; // Button connected to digital pin 2
Int ledPin = 13; // LED connected to digital pin 13
Void setup() {
PinMode(buttonPin, INPUT);
PinMode(ledPin, OUTPUT);
}
Void loop() {
If (digitalRead(buttonPin) == HIGH) {
DigitalWrite(ledPin, HIGH); // Turn on the LED
} else {
DigitalWrite(ledPin, LOW); // Turn off the LED
}
}
“`
Explaining the Code
In the setup function, we define the buttonPin as an input and the ledPin as an output. This ensures that the Arduino correctly recognizes the button and controls the LED.
In the loop function, we employ the if-else structure. The if statement checks whether the buttonPin reads a HIGH signal, indicating that the button is pressed. If it is true, the LED is turned on by setting the ledPin to HIGH.
However, if the if statement evaluates to false, meaning the button is not pressed, the else statement is triggered. Within the else block, we set the ledPin to LOW, effectively turning off the LED.
Testing the Code
Once we have uploaded the code to our Arduino board, we can now test it. When we press the button, the digitalRead function detects the HIGH signal from the buttonPin. Consequently, the if statement evaluates as true, and the LED turns on.
Conversely, when we release the button, the digitalRead function senses a LOW signal. This causes the if statement to be false, triggering the else statement. As a result, the LED is turned off.
Understanding the fundamentals of button and LED circuits and how to code them allows us to create simple yet impressive electronic projects. With a basic understanding of how buttons connect with wires and how code controls the behavior of LEDs, we can embark on more complex projects and broaden our knowledge of electronics. So go ahead and experiment with buttons and LEDs the possibilities are endless!
By assigning English names to pins and using conditional statements, we can make our code more readable and easier to understand. This not only helps us in the development process but also makes it easier for others to comprehend and modify our code.
Remember to always comment your code and explain your logic to make it even more clear for anyone who reads it.
The if statement provides a powerful tool for conditional execution in programming. By using this statement, we can selectively run code based on specific conditions, allowing for greater flexibility and control within our programs. Understanding how to construct and utilize if statements is essential for any developer, and opens up a world of possibilities in program design.
References:
– Diez, C. (2021, July 15). “Arduino Tutorial: If Statements and Conditional Execution”. The Engineering Projects. [ ]
The else statement is a vital component of programming that allows us to create alternative paths in our code. It provides a fallback plan when the conditions stated in the if statement are not met. By utilizing the else statement efficiently, we can enhance the functionality and versatility of our programs.