Arduino Statements

Arduino – Switch Statements

The switch statement, in Arduino programming, is very similar to the if statement that I wrote about previously. The main similarity is that you’re testing a statement, if it equals true, certain code is ran.

The difference is versatility and ease of use. When looking at a switch statement, it appears to be much more complicated than an if statement. It’s not! Actually it is much more simple to use, and produces a lot less code.

You will thank yourself later for making the switch, the switch statement switch.

What is it?

Without showing you any code right away, I’ll explain what it is in human language.

A switch statement takes a variable as an argument, and evaluates it. The actual switch part comes after. Now that it knows what it’s dealing with, it looks at the possible matches that you’ve preselected. When it finds a match, it runs the code until it comes across the word “break”. The break makes it skip the whole rest of the switch statement.

If there is no match, it runs the default code. The default code can be blank, and doesn’t have to contain anything juicy. A lot of the time, my default code just outputs to serial saying there was no match.

Uses

An example, where you would use a switch statement in the real world, could be in actual smart home light switches. Maybe you have a function that toggles them off and on when your cell phone app communicates with the arduino.

You could have the communication set a variable based on what button was pushed. Then the variable gets passed in to the switch statement. The switch statement sees the variables value of “living room” and associates it with what it knows, which may be switch number 3. Then inside your statement it can set variables and call functions based on switch 3.

And then you have light on, light off. This statement can reduce a lot of code, where you may otherwise have to write a function or if statement multiple times.

Or you may decide to put the switch statement inside the function, which would produce the same result as the function being inside the switch.

Usage

This begins with a variable that you’re going to test. This variable can be anything, an int, a string, char, etc. You start the switch statement with “switch (var)”. The “var” is where you’d place the name of your variable.

Much like other things you come across while programming for Arduino, you place the code to be run in curly braces. { and }

The difference here, from the other statements, is that the conditions that you are testing reside inside the curly braces. Normally your arguments would go inside the parenthesis, not today!

The way you compare what your variables value is, looks like this: “case condition1:”. You’d replace condition1 with the value you’re testing against your variable. For example, if you’re trying to see if a string says “taco”, you’d replace condition1 with the word taco. It would say “case taco:”.

Ending each code block after you define your case is very important. You end it with break;. If you do not break out of your code, either the compile will fail, or you’ll end up with unexpected results. This is the only time you do want to break your code, instead of fixing it.

 

The last part of this is the default portion. You define the default code to be run by calling “default:”. Any code between the “default:” and the “break;” is run if none of the other things you defined turned out to be true. Sometimes there are errors that cause the variable not to be set right, sometimes you planned on using default for multiple cases. Whatever the case is that you’re using default, you will know. I’ll say again, that you do not have to use the default section. It does need to be there, but it can be simply “default: break;” if you want your switch ignored when nothing is true.

Examples

This example will be assuming the ability to read based on the age of the person. We’ll start by defining the age variable:

int age = 0;

Then we’ll initialize Serial 0, so we can output to the pc:

void setup() {
 
Serial.begin(9600);//Initialize pc communication

}

In the loop we tell switch what variable we’re testing, and what each condition will do. In this case we’re just outputting different words to the serial monitor. After the switch statement is over we do age++, this simply increments the int by 1. You can increment any int this way, and if you have it being done in loop, it’ll just keep on adding. After we have a 5 second delay, before the loop starts over again.

void loop() {

switch(age) {
 case 1:
 Serial.println("You're only 1, how can you read this!");
 break;
 case 2:
 Serial.println("You're only 2, you can talk, but surely still can't read.");
 break;
 case 3:
 Serial.println("You are 3, I'd be pretty impressed if you could read.");
 break;
 case 4:
 Serial.println("You're 4, you may be able to read, but I still don't believe you.");
 break;
 case 5:
 Serial.println("You're 5, I guess it's time to start reading.");
 break;
 default:
 Serial.println("You are either older than 5, or younger than 1. Do whatever you want, I guess...");
 break;
}
age++;
delay(5000);//wait 5 seconds
}

I’ll paste the entire code now, if you’re copying and pasting it, you can use this one:

int age = 0;

void setup() {
 
Serial.begin(9600);//Initialize pc communication

}

void loop() {

switch(age) {
 case 1:
 Serial.println("You're only 1, how can you read this!");
 break;
 case 2:
 Serial.println("You're only 2, you can talk, but surely still can't read.");
 break;
 case 3:
 Serial.println("You are 3, I'd be pretty impressed if you could read.");
 break;
 case 4:
 Serial.println("You're 4, you may be able to read, but I still don't believe you.");
 break;
 case 5:
 Serial.println("You're 5, I guess it's time to start reading.");
 break;
 default:
 Serial.println("You are either older than 5, or younger than 1. Do whatever you want, I guess...");
 break;
}
age++;
delay(5000);//wait 5 seconds
}

Let’s see what happens when we run the code!

switch output

Exactly what we were hoping for! It counts from zero to a bazillion, and correctly chooses what switch condition to use.

Let me know if you have any questions below! More than happy to answer them.

Arduino Statements

Arduino – If Statements

Welcome to If Statements! This is where you will learn to argue with your Arduino about whether or not a statement is true. If statements are very commonly used, get to know them well. Disclaimer: You will not win an argument with your Arduino, it always knows if a statement is true or not. This is similar to marriage, you may find yourself upset if you choose to argue with your Arduino.

What you need:

What is it?

An If Statement is a block of code that gets run depending on an statement you supply to it. If the statement is true, the block of code is run. If the statement is not true, it skips the block of code.

If you supply an else if statement, it will test that statement to verify if it’s true.

If that else if statement is false as well, and you supply an else statement, it will skip to the else statement and run that code block.

You don’t have to supply an else if statement, if your first if statement is false, it will go directly to else. You also don’t have to supply an else statement, if the first if statement is false, it would just not run the code at all without an else statement.

Uses

A good example of an if statement would be in a weather monitoring application. You could have a device monitoring the temperature, and if the temperature is below 32 degrees Fahrenheit, it will tell you ice is possible on the roads. An else statement for this could be an output stating that the roads should not have ice on them.

Another example would be when using an RFID tag. You could have a list of acceptable RFID tags, and if the one that is scanned belongs to the list, the door opens. An else statement for this would be a red blinking LED, that indicates a RFID tag that is not allowed access.

Usage

Lets look at the anatomy of an if statement.

The syntax from Arduino.cc looks like this:

if (condition)
{
  //statement(s)
}

Statement to be tested

Declaring the statement starts with “if ()”, you must have parenthesis here. In between the parenthesis, you put the condition that you’re testing. An example would be “if (x > 10)”. If x is 11, it would run the code. If x is 1, it would not run the code.

Code to be run

The second part of this is the curly braces { and }. This is where you put the code to be run. Anything outside these braces will be run, regardless of whether the condition is true. Inside the braces is code to be run if the statement is true.

If the If gets run, the others are ignored

The main thing to remember here, is that if any if statement equals true, the code gets run and any other part of the if statement is ignored. This means that it skips any else if, or else statements.

Examples

Simple predefined variable:

This example uses a predefined variable, which is an integer named age. This variable is declared right at the top of the following code. Here we’re trying to figure out if the person is old enough to drink. In this case the person is 14, so it should determine that the persons age is under 21, and run the else statement.

int age = 14;

void setup() {
 
Serial.begin(9600);//Initialize pc communication

}

void loop() {

if (age < 21) {
 Serial.println("You are not old enough to drink!");
}
else {
 Serial.println("You are 21 or older, you may have a drink.");
}
delay(5000);//wait 5 seconds
}

Let’s run the code, and see what we come up with. If you’re unsure how to upload code, check out my hello world post. Here is the output you should expect from the above code:

Success! It determined that we are unable to drink.

Let’s change the age variable to 24 now, and see what we get.

int age = 24;

The Arduino wins again! If statements are very useful when writing Arduino sketches. You’ll find yourself using them quite often. Let me know in the comments if you have any questions, and please subscribe for additional Arduino tips.

If you’re looking for something a little more versatile, you may try Arduino Switch Statements.