If Statement Conditionals

Learn Programming and Electronics with Arduino - A podcast by Programming Electronics Academy

Categorie:

If Statement (and else-if), Comparison Operators and Conditions In the last lesson, we learned about the if statement. The if statement was the perfect choice for setting up instructions to run only when certain conditions were met. “If 30 seconds has passed – stop the heating element” or “If the sensor perceives a wall – turn 180 Degrees”. This lesson will expand on this amazingly useful function and show you how to stack different conditions to satisfy the flexibility you want in your designs. If you like this tutorial, click here to check out FREE Video Arduino course – thousands of people have really enjoyed it. You Will Need Potentiometer (doesn’t matter what resistance range) 220 Ohm Resistor LED (any color) Jumper Wires (3) Alligator Clip Dull machete with wood handle Step-by-Step Instructions Place the potentiometer in the breadboard. Place a jumper wire from one of the outside leads of the potentiometer to the 5V pin on Arduino. Place a jumper wire from the other outside lead of the potentiometer to one of the GND pins. Place the final jumper wire from the center pin of the potentiometer to the A0 pin. Connect either side of the 220 ohm resistor to pin 13. Connect the short leg of the LED to GND (the GND pin next to pin 13 is the most convenient). Attach the other leg of the resistor to the long leg of the LED. Plug your Arduino into your computer with the USB cable. Open the Arduino IDE. Open the sketch for this section. Click the Verify button (top left). The button will turn orange and then blue once finished. Click the Upload button. The button will turn orange and then blue when finished. Open up the Serial Monitor window. Tools > Serial Monitor. Adjust the potentiometer and watch as the LED turns on and off based on the knob position. If Then Statement Conditionals Set up This image built with Fritzing. /* Conditionals - If statement This example demonstrates the use of if() statements. It reads the state of a potentiometer (an analog input) and turns on an LED only if the potentiometer goes above a certain threshold level. It prints the analog value regardless of the level. The circuit: * potentiometer connected to analog pin 0. Center pin of the potentiometer goes to the analog pin. side pins of the potentiometer go to +5V and ground * LED connected from digital pin 13 to ground * Note: On most Arduino boards, there is already an LED on the board connected to pin 13, so you don't need any extra components for this example. created 17 Jan 2009 modified 9 Apr 2012 by Tom Igoe This example code is in the public domain. http://www.arduino.cc/en/Tutorial/IfStatement */ // These constants won't change: const int analogPin = A0; // pin that the sensor is attached to const int ledPin = 13; // pin that the LED is attached to const int threshold = 400; // an arbitrary threshold level that's in the range of the analog input void setup() { // initialize the LED pin as an output: pinMode(ledPin, OUTPUT); // initialize serial communications: Serial.begin(9600); } void loop() { // read the value of the potentiometer: int analogValue = analogRead(analogPin); // if the analog value is high enough, turn on the LED: if (analogValue > threshold) { digitalWrite(ledPin, HIGH); } else { digitalWrite(ledPin, LOW); } // print the analog value: Serial.println(analogValue); delay(1); // delay in between reads for stability } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 /* Conditionals - If statement This example demonstrates the use of if() statements. It reads the state of a potentiometer (an analog input) and turns on an LED only if the potentiometer goes above a certain threshold level. It prints the analog value regardless of the level. The circuit: * potentiometer connected to analog pin 0. Center pin of the potentiometer goes to the analog pin. side pins of the potentiometer go to +5V and ground * LED connected from digital pin 13 to ground * Note: On most Arduino boards, there is already an LED on the board connected to pin 13, so you don't need any extra components for this example. created 17 Jan 2009 modified 9 Apr 2012 by Tom Igoe This example code is in the public domain. http://www.arduino.cc/en/Tutorial/IfStatement */ // These constants won't change: const int analogPin = A0; // pin that the sensor is attached to const int ledPin = 13; // pin that the LED is attached to const int threshold = 400; // an arbitrary threshold level that's in the range of the analog input void setup() { // initialize the LED pin as an output: pinMode(ledPin, OUTPUT); // initialize serial communications: Serial.begin(9600); } void loop() { // read the value of the potentiometer: int analogValue = analogRead(analogPin); // if the analog value is high enough, turn on the LED: if (analogValue > threshold) { digitalWrite(ledPin, HIGH); } else { digitalWrite(ledPin, LOW); } // print the analog value: Serial.println(analogValue); delay(1); // delay in between reads for stability } Discuss the Sketch In this sketch we measure voltage at an analog pin from 0 to 1023 – this voltage changes based on where the knob of the potentiometer is set. We then define a threshold value somewhere in this range, let’s pick the number 400. When the value measured at the analog pin is above 400, we turn on the LED at pin 13, when the voltage is below 400 we turn the LED off. It’s as easy as that. Make sure you read the sketch and try to figure out what is taking place before moving on. This program might look long to you – the previous ones were a bit shorter. A good way to approach any program long or short is to cut it up into chunks and only consider pieces of it at a time. The first chunk in this sketch is the multi-line comments that clearly describe: What the program will do Generally how the program will accomplish it How to set up the circuit and the components you will need Any pertinent notes The license the program is released under (if any) The author, date and version number This might seem like a lot of stuff – but I would recommend you do the same thing for your programs! This information will not only help you understand what the heck you intended when you wrote the program but if you make the program available for others then your comments will help them as well. Some of the functions that are now integrated into the Arduino IDE were created by people just like you – they had a problem, they found a solution with some well-written code, they made it available to all the Arduino users in the world – and everybody else found it useful – and before you know it your code is famous and you win the Nobel peace prize. Enough of this tirade, let’s move onto the first block of code that will be executed by the Arduino. const int analogPin = A0; // pin that the sensor is attached to const int ledPin = 13; // pin that the LED is attached to const int threshold = 400; // an arbitrary threshold level that’s in the range of the analog input 1 2 3 4 5 const int analogPin = A0; // pin that the sensor is attached to const int ledPin = 13; // pin that the LED is attached to const int threshold = 400; // an arbitrary threshold level that’s in the range of the analog input Notice that all the variables have const in front of them. This keyword stands for constant. A constant is classified as a qualifier – it adjusts the behavior of the variable being declared. It is similar an adjective in a sentence – “The squishy material,” squishy qualifies what the material will behave. It might seem counterintuitive to the whole point of variables, but the constant qualifier will stop the variable from changing throughout your program. It protects the value from start to finish. Why do this? It protects you from unintentionally writing a new value to the variable. It happens more often than you might think – I recommend using constants when the variable will not change in the program. The integer constants we declare are pretty straightforward. The variables analogPin and ledPin are those pins the potentiometer and LED will be attached to on the Arduino board. Threshold is the arbitrary number chosen as the condition to turn our LED on or off. The next block of code is setup(). Here, we have to set the mode of a pin and set up serial communications. void setup() { // initialize the LED pin as an output: pinMode(ledPin, OUTPUT); // initialize serial communications: Serial.begin(9600); } 1 2 3 4 5 6 7 8 9 10 11 void setup() { // initialize the LED pin as an output: pinMode(ledPin, OUTPUT); // initialize serial communications: Serial.begin(9600); } Recall that all pins are by default set to INPUT, so we do not have to explicitly set the pin mode for our analogPin A0 as an INPUT – though I would argue it is best to do so for clarity. You should have serial communication down pat. We use the begin() function from the Serial library with a baud rate of 9600. Now that we have things setup, let’s get into the loop(). The first line of code we encounter reads from the value at the analog pin A0 and assigns this value to an integer variable called analogValue. int analogValue = analogRead(analogPin); 1 int analogValue = analogRead(analogPin); To do this, we use the analogRead() function. Recall that analogRead() will return a value between 0 and 1023. This value will change as we adjust the potentiometer. This line of code is checking the position of the potentiometer every time through the loop(). The next thing we want to do is compare the value we just read from the analog pin to our threshold value. The if-else statement is perfect for this. if (analogValue > threshold) { digitalWrite(ledPin, HIGH); } else { digitalWrite(ledPin, LOW); } 1 2 3 4 5 6 7 8 9 if (analogValue > threshold) { digitalWrite(ledPin, HIGH); } else { digitalWrite(ledPin, LOW); } You have seen the if statement before, now we add an else statement. The if statement checks a condition in the parenthesis, if it is TRUE, then the code in the curly brackets is executed – if the condition is not met (FALSE), then it moves to the else statement. Consider this pseudocode: if(apple is NOT rotten) { } else { } 1 2 3 4 5 if(apple is NOT rotten) { } else { } You can see that the else statement gives you control over what to do when the condition in the if statement is not met. In a later lesson we will talk about the else-if statement which will offer even further control over conditions. Explanation of iF-Then Statements In this example the condition we are interested in is: In this example the condition we are interested in is thus… analogValue > threshold 1 analogValue > threshold If this is TRUE we turn the LED on by using the digitalWrite() function: if (analogValue > threshold) { digitalWrite(ledPin, HIGH); } 1 2 3 4 5 if (analogValue > threshold) { digitalWrite(ledPin, HIGH); } If this condition is FALSE we turn off the LED by executing the code inside the curly brackets of the else statement: else { digitalWrite(ledPin, LOW); } 1 2 3 4 5 else { digitalWrite(ledPin, LOW); } Before we continue discussing the sketch, let’s do a quick overview of Comparison Operators. The condition set in an if-else statement will use what are called comparison operators. The list of comparison operators on the Arduino Reference page is as follows: == (equal to) != (not equal to) < (less than) > (greater than) >= (greater than or equal to) These operators offer a broad spectrum of comparisons to use. It’s vital to pay close attention to the syntax of the comparison operators. Accidentally dropping an equal sign, or typing a > instead of a < is easy to do, and usually leaves you scratching your head when the program acts differently than you might have expected. Now that we have turned the LED on or off depending on the position of the potentiometer, let’s see exactly what values are being read. We want to do this to ensure the program is doing what we think it should and also to make sure our potentiometer (sensor) is working properly. // print the analog value: Serial.println(analogValue); 1 2 3 // print the analog value: Serial.println(analogValue); This line of code uses the println() function from the Serial library – which (as you know by now) sends the values from the Arduino to your computer. Adjust your potentiometer and watch the values change in the Serial Monitor window. Then adjust the potentiometer so the value is right at the 400 threshold and make sure the LED is responding appropriately. Finally, we want to slow down the readings to add some stability. We do this with the delay() function. delay(1); // delay in between reads for stability 1 delay(1); // delay in between reads for stability Let’s recap. First we read the value at the analog pin and assign that value to a variable. Next we check if that variable is more than or less than our threshold value. If it is above the threshold the LED turns on, if it is below the threshold the LED turns off. We also want to see the actual values at the analog pin, so we print them to the serial monitor. Finally, we wait a millisecond before our next reading – which starts the loop() at the top. You can see how handy the if-else statement can be. As I have said previously, the if-else statement is a staple of programming – you will see it (or a similar form of it), in any programming language you encounter henceforth. Try On Your Own Challenges Adjust the value of the threshold variable. Write an additional if statement to turn on the LED when the analogValue variable is less than 100. The LED should turn on when analogValue is greater than 400 and less than 100. Further Reading If-Else Statement – From the Arduino Reference More on the If-Else statement – The example sketch on the Arduino Website

Visit the podcast's native language site