Arduino MASTERCLASS | Arduino Programs? How to Use Control Structures PART 6
Transcript:
Arduino is a great tool for controlling electronic stuff like sensors and motors. But if you wanna build logic into your Arduino program, then you need to understand how to use control structures in your code. In this lesson, we are gonna go rapid fire over several super useful control structures, probably the most important ones. By the end of this lesson, you’re gonna have an understanding of how they work and how to use them. Let’s go.
Now this video is part of a series and where we left off was talking about variables. So if you haven’t already, I highly recommend after you watch this video, going back and watching the previous lessons. So far, we’ve talked about how every Arduino program is laid out, then we talked about using variables we’ve gone over a little variable example. We sprinkled in a couple of these most important Arduino specific functions, namely pinMode and analogWrite. But now we’re gonna start talking about these control structures. What is a control structure? A control structure allows you to adjust the flow of your code. If we go to the Arduino Reference page and we go to Structure, when I’m talking about control structures, I’m talking about these right here. So we have an if statement, fors, else, whiles, switch cases. These are the control structures that are going to allow you to have your code do different things depending on different circumstances. So let’s go back to that code and we’ll see we have this if statement, so this is some control code and notice it’s followed by an opening and a closing parenthesis and inside this is called our condition. So if statements have a condition. If the condition evaluates to true, then the code inside the curly braces gets run. If the condition evaluates to false, then all the code in here just gets skipped over. So you only do the stuff inside the curly braces of an if statement if this is true. Now you might be looking at this and being like, “Wait, what is going on here?” Well, we’ve got two things going on. So this right here is actually an or symbol. So this condition is saying if the brightness variable is less than or equal to zero, or if the brightness variable is greater than or equal to 255, then do something. So, well, why don’t we just evaluate? Let’s pretend we’re the Arduino and let’s evaluate this. So what did we say? We said brightness was five. So if brightness is five, is five less than or equal to zero? Nope, it’s not. Is five greater than or equal to 255? Nope, it’s not. So that means we’re just gonna skip over this line of code right here, the first time through the loop. So we’ve controlled our code flow, because we haven’t used this based on a condition. So then we get to this next line of code and it says delay 30. Here’s another one of those super important Arduino functions that you’ll learn to love and hate. It’s called delay and what it does is it stops the program in its tracks. No other code will run for the amount of time you put in here and this time is in milliseconds. So for 30 milliseconds, we’re gonna say, “Stop. Don’t do anything, Arduino board.” And when we say, “Stop, don’t do anything,” what we’re saying is, “Don’t execute any more code,” because what we did up here on line 13, when we PWM-ed pin nine to a value of zero, that means the LED was off, there’s no brightness there and we’re just gonna hold that position. So delay is like, “Hold it, hold it. Okay, go.” That’s what’s going on here. So after the delay, we get to this final curly brace. Here’s the end of this loop function and what do we do? We start back up at the top. So we’re back at the top. We run into our friendly function, analogWrite, again, using the PWM feature of the microcontroller and what is brightness this time? Well, if you recall last time through, we changed brightness to five. So now brightness is five. So that increases the on time for the duty cycle and that means this LED is gonna be on ever so slightly, so now, the LED is gonna turn on dimly. Now, it’s not gonna turn on dimly, because we’ve applied a lower average voltage to it. It’s actually gonna come on dimly, because of the ways our eyes work. So the LED is gonna be flickering on and off at a rapid pace. It’s not gonna be somewhat on and somewhat off. It’s gonna be full on and full off, but the frequency of it coming on and off tricks our eyes into thinking that it’s actually dimly lit and that’s how PWM works with LEDs. You’re able to make a fading effect of the LED by adjusting the duty cycle of that PWM signal. All right, so we can see the LED dimly. Well, down here, what do we do? Well, now we’re gonna take brightness, that was five, and we’re setting it equal to brightness plus fade amount. Well, what is brightness? You might be tempted to think, “Well, hey, yeah, we set brightness to zero up here.” Well, actually brightness got updated before, so we’re working with the newest, the latest and greatest brightness, which was five. So five plus fade amount, which was set to five. So that’s 10, so now brightness is equal to 10. Now we come back down to our if statement and we are checking the condition, but the condition really isn’t changed. ‘Cause 10 isn’t less than or equal to zero, nor is it greater than and equal to 255. So again, we’re just gonna skip this code. Now we delay, we say it, “Hold it, everybody.” We come back and you can see we’re just going through this over and over again. And what is happening? What’s happening is brightness, this value, because of line 16, it keeps increasing. It gets bigger and bigger and bigger and so we see this LED fade on slowly. It’s gonna get brighter and then brighter and then brighter. So we’re gonna see it fade on from dark to brightness. Well, what happens when this value gets to 255? Well, when this value gets to 255, then this if statement, this condition is gonna be true because brightness will be equal to 255, which means the code in here is gonna run. So our control structure is gonna affect that flow when brightness gets to 255 and what does it do? Well, it flips the sign of fade amount, so it’s this fade amount, which was five, it sets it equal to negative fade amount, which makes it minus five and then we delay. So that’s interesting. Minus five? So we said brightness was 255, so we come up to this loop. Brightness is still 255, so that LED is gonna be fully bright, fully lit. We come down to brightness. Now brightness, that’s 255 plus negative five. So what’s a positive number plus a negative number? Well, you basically do a subtraction. So now we’re gonna go down to 250. So now we’ll be going from a high brightness to a low brightness ’cause fade amount is negative so we’ll be subtracting from brightness until we get down to zero and then this if control statement is gonna flip it again and then we’ll add and it’s just gonna go back and forth forever and ever and ever and that’s just a basic idea of how this flow works. So let’s look at another example of a control structure. Let’s look at a switch case statement. Here’s an example of another control flow mechanism function called switch case. And what we’re doing here is we have a sensor hooked up to one of our analog pins and if you recall, the analog pins are connected to the analog to digital converter on the microcontroller. So pins A0 through A5, six pins on Arduino Uno using that ADC. And what that ADC is able to do is take in an analog voltage and convert it into a number between zero and 1,023. So what this program’s doing is it’s gonna read the value of the sensor and then based on what that input is, it’s gonna print out something different to the Serial Monitor. Now we haven’t talked about the Serial Monitor, but we are in a second ’cause it’s super important when you’re using the Arduino IDE, but let’s start at the very top here. Look, we’ve got two variables. They’re both integers. One is called sensorMin and one is called sensorMax. sensorMin was assigned to the value of zero and sensorMax, see, we’ve initialized it to the value 600, but what’s this C-O-N-S-T in front? Well, this is constant and what this is saying is, “Hey, these variables aren’t gonna change throughout the program.” This is called a qualifier and you’ll see this pretty often. You only use this for variables that don’t change. Here we are in the setup. And we see a super important function called Serial.begin. So there is a code library called the Serial library and begin is a function that’s part of that library. And so to use the begin function, first, we write the name of the library, which is Serial. We have a little dot and then we follow it with the name of the function, begin. And we’re passing into it this value, 9,600, which is the baud rate. All seems odd, just a lot of details here I’m skimming over, but essentially what this does is it allows us to communicate on the serial port between our Arduino board and our computer. So there’s a tool built into the Arduino IDE called a Serial Monitor, open it up right now. And what it does is it allows us to display text from the Arduino board to our computer. So Serial.begin initializes that Serial communication. Super important function, don’t worry about the 9,600 now. Just go with it. Again, it’s just the rate of communication. So we go through setup then we jump into the loop. What’s loop do? It goes over and over and over again. Now what are we doing here inside the loop? Well, it looks like we are declaring a variable and initializing it to a value. So we’re making an integer, we’re calling it sensorReading. And we set it equal to what? What is this? Well, this is a function. We see the name and then we see these parentheses here. analogRead is another one of those super duper important Arduino functions. analogRead uses those analog pins, so analog pins zero through six and it allows us to use the ADC to read a voltage. But all it needs to know is, “Hey, what pin number do I need to read that voltage at?” And so we’re saying pin A0. So if you wanna refer to those analog pins, you can use A0, A1, A2, A3, A4, A5. So you just put in A in front of the number. Now we could have made a variable out of this. We could have made a byte called sensorPin and set it equal to A0. We could have made it a constant since it’s not gonna change. And then we could have taken sensorPin and put it right here, just like that. So now what’s gonna happen on this line of code is that analogRead is gonna look at this sensorPin, pin A0, it’s gonna read the voltage and whatever the ADC returns, it’s gonna be a number between zero and 1,023, it is gonna store it into sensorReading. So now sensorReading is gonna be equal to whatever that value was. Line 14, a little bit confusing. It’s using a map function. Now this is a Arduino-specific function. It’s not super duper important, it’s still useful. What map does is it takes one range and it converts it into another range. Basically, what’s gonna happen is you pass in the existing range and then you want to transform it into a new range. I’m not gonna go into it now, but basically, what it’s gonna do is it’s gonna squish down the number so as that sensor value changes, we’re either gonna get a zero, a one, a two or a three. And that’s when we finally get to this switch case here. So the switch, notice that there’s a parenthesis following it and inside, there is a value and this value is gonna determine which case we actually take on. So here we’ve got case zero. So when the value is zero, we’re gonna execute this code. When the value is one, we’re gonna execute this code. When the value is two, this code and when the value is three, this code. Notice the break statement after the case that says, “Hey, when you get to the break statement, it’s gonna jump us out of that switch case.” So you’re only going to do one of these cases. So in this loop, we’re gonna read the value at the sensor, we’re gonna map it to a small, condensed range and then we are gonna do something based on the value. And in this case, we’re using the Serial library again, but we’re using the println function from the Serial library. And this is what is actually gonna print something out to the Serial Monitor window. So after we get down to the end of the switch case, we have a short delay, just one millisecond and then we jump back up to the top of the loop and what do we do? Well, we read the sensor again. Well, why would we read the sensor? We just read it, didn’t we? Well, we’re gonna read the sensor, because the idea is that our Arduino is constantly checking the sensor. It’s always on a lookout. “Hey, did the sensor change? Did it change again? Is something different?” So every time through this loop, which is running rapidly, the Arduino’s on the lookout for a change. And when it sees a change, this switch case can react differently. So I’ll go ahead and upload this and I’m gonna open up that Serial Monitor window and you’ll see it’s low. And the sensor I have attached, I actually just have a potentiometer attached and a potentiometer is like a dial, think of like on a amplifier or on an old school radio as you turn that dial to change the station. So I’m just gonna slowly change this and you can see as I change that, the value is changing, sensorReading is changing, ’cause the value at sensorPin is changing. And as I adjust it lower, it’s doing that as well. So you can see, again, how this control structure is helping us adjust what happens in the sketch itself. All right, we’re gonna look at one final sketch and that’s gonna cover some of those other super important Arduino functions. So let’s go to File, Examples, Button. So now this is a sketch that is gonna check for a button press. So this circuit looks something like this. We’re gonna have an LED attached through a 220 ohm resistor to pin nine, the other side going to ground, but then we’re adding in a button. One side of the button is connected to pin two. The other side of the button is connected to ground. So you can forget about the potentiometer, just look at the LED and the button here. So what we want this code to do is look at that button and we want to change how the LED is reacting based on what the button’s doing. So in this case, when we press the button, the LED is gonna turn off. And when we’re not pressing the button, the LED is gonna be turned on. So what do we have at the top? We’ve got some variables. Should be familiar with these by now. We’ve got buttonPin, we set that equal to two and ledPin, we set that equal to nine. Again, that’s where we’ve connected our hardware, the button at pin two and the LED at pin nine. These are set as integers. They could be bytes but it’s okay to have them integers and then they’re qualified as constants. They’re not gonna change. So that’s why they’re made as constants. But then we have a variable called an integer called buttonState and it’s set equal to zero. Now the button can either be on or off so we could have set this equal to a boolean, but setting it equal to an integer is fine, too. Then we get to our setup function and we’re using the pinMode again. So we can use the pinMode function to set those pins as outputs like we’re doing with the LED, we’re setting it as an output. Or we can set a pin as an input. So we could just do INPUT like this, but we can also set it to an INPUT_PULLUP. Now I won’t exactly get into what pull-up resistors are and all that stuff right now, but basically, what it’s saying is, “Hey, we’re gonna set this pin to a high state and if you want it to change, you need to pull it to a low state.” But for all intents and purposes, we’re saying, “Hey, we want that buttonPin, that pin two, to be an input.” And if we wanted, we could just do input. But in this case, we’re just gonna go with INPUT_PULLUP. All right, so in setup, which only runs once, we’re gonna use pinMode to set one pin as an output and one pin as an input, and then inside the loop, what do we do? Let’s see, first line of code we come into, we’ve got our variable, buttonState. It’s set equal to zero now and we’re setting it equal to this function, digitalRead, buttonPin. So here’s another super important Arduino function, digitalRead. We know it’s a function because it’s got those parentheses. It takes a value in here and it’s a reserved function name. It changes to the color orange. And what digitalRead’s gonna do is it is gonna read the voltage at that buttonPin And it’s gonna check whether the voltage is high or whether the voltage is low. Now in our case, when we are not pressing this button, since we made this an INPUT_PULLUP, pin two will read high. But when we are pressing that button, what we’re doing is we’re introducing ground voltage and so, pin two is actually gonna read ground voltage when we press the button. So that would be a low voltage state. So when we don’t press the button, this is gonna be high and when we do press the button, it’s gonna be low. High is represented by a one and low is represented by a zero. So if we don’t press the button, then digitalRead is going to return a value. What’s that value gonna be? If we’re not pressing the button, it’s gonna be a one. So then buttonState would be assigned the value one. And then we get to some control flow. We’ve got our friendly if statement and we look at this condition in this control flow and it’s saying, “Hey, buttonState == high.” Hey, what is this? Isn’t that an assignment operator? Well notice that it’s said equal-equal. This is actually checking for equality. So it wants to know, “Hey, is buttonState equal to high?” Well, we said it was, because digitalRead, it was reading buttonPin. If we’re not pressing the button, it would be a one, it would be high. So this is true and if that’s true, we would run the code inside the if statement. And in this case, we come to another super important Arduino function, digitalWrite. So we had digitalRead a second ago. That’s for reading digital inputs, either on or off inputs and digitalWrite is for creating an output on those digital pins, either a high voltage or a low voltage. So digitalWrite, it’s gonna take two values. First, it needs to know what pin to apply the voltage at and then either a high voltage or a low voltage. So in this case, the voltage is gonna be high. We want that LED to be on if we are not pressing the button. So now we see another part of this control flow. It’s called an else. So notice that the else comes right after the end of this if statement and it’s got its own curly braces. and what this else is doing is saying, “Hey, if the if statement is false, so if this is not true, go ahead and do this other thing.” So if this, else, do this. So if we’re not pressing the button, then we’re gonna write the voltage to ledPin low. So what this control flow is gonna allow us to do is check the current buttonState, and then whether or not it’s pressed, it’s gonna do one thing or another thing. Now we could make this an else-if, and if we add the if there, we add another if, we could add another condition in here. Like maybe we had two buttons and we said, “If the other button is high, then do this.” I won’t do that now, but just want to let you know that that’s something that you can do. All right. I know that was a lot. We talked about how every Arduino program is laid out with setup and loop, we talked about variables, how they’re buckets for storing information, how you can declare them and initialize them and the different data types there are. We talked about a couple control structures, namely the if statement, the if-else, and also the switch case statement. Now there’s a lot of other control structures that are really useful. For example, a for loop and a while loop. We won’t get into those now. And then throughout this whole conversation, we’ve been talking about the most important Arduino-specific functions, the pinMode function, digitalWrite, digitalRead, analogWrite, analogRead and then the Serial library function, Serial.begin and Serial.print and Serial.println and then finally the delay function. Now I know that’s a lot to take in, but really, that just laid most of it out right there for you. It’s really these basics that allow you to do tons of stuff. So all the stuff we talked about here is core critical stuff that you need to get into your brain and practice, play around with. Go on to those example sketches. See if you can see any of this stuff, see if you can follow some of the control flow. Now we’ve only scratched the surface, though. It’s gonna get really exciting, ’cause we’re gonna start talking about Arduino libraries and what Arduino libraries are gonna let you do is start using all different types of hardware by simply using other people’s code. So we’ll look at some examples of how libraries work with Arduino and how you can leverage them to get your prototypes running super fast. If you have any questions about this lesson, you can leave your questions in the comments. I will do my very best to answer them. I would love if you could like this video if you enjoyed it and subscribe to the YouTube channel. I look forward to talking to you about Arduino libraries next.