In this section, we'll dive into using 'switch' cases to implement comparative lists and outcomes.

Transcript

So far, we've looked at the most common types of loops and statements, which you can use to accomplish many different projects. But as with most things in programming, there is usually a simpler way to do things. If statements are so useful and creative for implementing if-this-then-that logic. But if you have a number of different possible outcomes for a single event, then you'll end up using a long list of if-statements comparing the same value. And that'll work just fine, it's not a problem, but there are better ways to do it. Which brings us to using switch cases. A switch case allows you to use a variable or value, and create a series of outcomes or cases, depending on the value result.

For example, imagine that you've got a variable which could be any number between 0 to 9. And what you want is something different to happen for each possible value. You could of course use a series of if-statements, which would look like this. Let's take a look at the Arduino IDE. So you could go into your loop and create if sumValue is equal to 0, then do something. Break out of that. If sumValue is equal to 1, break out of that and do something. You would end up with a very convoluted list, which is not what you want. You want it to be elegant and simple. Or you could use a switch case, which makes everything simpler and easier to understand. To create a switch case, you use the following syntax. Let's take a look.

So if we remove all of this, we use a switch case much in the same way as an if-statement. We write switch, and we put into brackets the variable that we would like to compare. So again, we use sumValue in our brackets, and we use the following syntax. We use case, and this is where it gets a little odd, a little different. We use case with a regular colon, so a double dot here, enter, and it doesn't recognize that as a new level, so you want to, for styling purposes perhaps, you want to hit tab. And then you can create whatever it is you want, and in case here, you put your value. So let's say, again we'll use the example 0, so case 0. The case where sumValue is equal to 0. We could do something here, and then much like our for loops and while loops, we use break, and that will exit that particular case.

And it can only ever perform, or it can only ever equal one case at a time. So we'll go through, and we'll create case 1, and we can do something here, and break out of that. Now what this means, is that it's not going to go onto case 0, and if something happens to change, goes onto case 1 again. We're using break, which breaks out of this switch here. Now of course you could not use break, and it will perform case 0, and go on and check the others, but generally that's not how you want to use switch cases. So break gets out of this switch, or performs whatever function it is, you could jump to another section of your code, perform a simple action, and then break out of it. Switch cases are super useful. So let's look at using something in a practical context.

So I've got the source code for the mini project here, and it's all pretty straightforward. We've got our pin definitions, a global variable, which we're calling last plot value, which we're going to keep track of whether our value has changed. So we're going to take a potentiometer, and wire it up to our board first, so we can explain the code as it's working. So again, if you remember back to our section on using analog pins, I'm taking one pin, connecting it up to ground, making sure to keep my head out of the way, connect the other pin up to 5 volts, nothing we haven't done before, and I'm connecting the middle pin up to A0, which is our pot pin. Fantastic. So now that we've got that set up, let's go through the code.

So we're setting up our pin as normal, initializing our serial port, nothing out of the ordinary there. Then what we're doing is we're taking pot value, and we're assigning it to the analog read of pot pin, which as we know, is 0 to 1023, it's a 10-bit value. And then we're going to divide it by 255. Why are we doing this? Well, it's going to give us 5 different values. If we divide 1023, or perhaps 1024, by 255, you will get 5. You get 5 different cases that we can use from 0 to 4, remembering that we're 0 indexing them. So let's go through and take a look at what we're doing. So it divides it by 255, which means the pot value will equal 0, 1, 2, 3, or 4, really simple integer numbers.

So case 0, so we've entered our switch case here. And above this, you can see we've got another if statement. What's that all about? Well, here, we're using another relational operator, which we looked at in some of the previous loops. And we're going to take a more in-depth look at in the next chapter on operators. So what we're saying here is if pot value is not equal to, you might have seen the double equal signs, which means is equal to, well, is not equal to is a check. And in the previous tutorial, where we were using a toggle value, we had it the other way around. We had, you read it left to right, is equal to not last pot value. But if we put the exclamation mark before, this is where the syntax is really important.

We're saying if pot value is not equal to, and so you can read it, and it actually makes sense when you read it English, if pot value is not equal to last pot value. And the reason for this is we're going to be printing out some outcomes based on the value of the pot. But if we didn't have this in here, is if we left it on the one value, it would keep printing and keep going through that switch case. But we only really want to know when it changes, we want to know if something different happens if it enters a new range, which is why we've got that check in there. And at the very end, you can see that we update last pot to equal what the current pot value is equal to.

Now switch zero, we're going to print out very low in the case of one, low case of two moderate, case of three high, case of four extreme. And then we're using an extra thing here called default. What's that? Well, it is equivalent to the else statement from our if statements. It's saying if none of these are true, if it doesn't meet any of those, it's a backup, a contingency, a default. So if none of those is equal, perhaps something's gone wrong on our board and we want to know about it. If none of those are true at the very end, then we print error and we break out of it. It's quite a simple project, but a lot of fun. So let's upload it and see how we go.

Handy trick, I'm using the shortcut control U or command U if you're on a Mac to upload your code, which saves you having to click the button all the time. So let's open up our serial monitor. So let's try turning all the way zero, sorry, all the way up. We can see that it goes to extreme. Now if we turn it back the other way, there's a little bit of jitter, a little bit of noise in the channel that goes from high to moderate to low to very low. And that's the range of our potentiometer. And that noise, why it's registering multiple times is a little bit of noise in the actual voltages that are going on there. So it's between this threshold and it's triggering back and forth. It's not a super clean trigger.

And there's ways you can, there's methods you can do to get around that and to filter that out further. But that's not really the point of this. It's beyond the scope. We're looking at switch cases and it's a really cool usage of taking a set of events and bypassing the need for long if statements, which will just clutter up your code, make it really hard to read. The equivalent of that in if statements would take up perhaps two, three, four times as much room depending on how you were styling it. So much cleaner and much simpler. So that's a bit about different logic statements. There's plenty more other things you can do such as do and try and different methods, but most projects can be accomplished using a combination of what we've covered so far. And to finish off the chapter, we're going to be looking at mathematical functions and operators and also functions in general, how to create your own.

Feedback

Please continue if you would like to leave feedback for any of these topics:

  • Website features/issues
  • Content errors/improvements
  • Missing products/categories
  • Product assignments to categories
  • Search results relevance

For all other inquiries (orders status, stock levels, etc), please contact our support team for quick assistance.

Note: click continue and a draft email will be opened to edit. If you don't have an email client on your device, then send a message via the chat icon on the bottom left of our website.

Makers love reviews as much as you do, please follow this link to review the products you have purchased.