Arduino: if and else command simply explained
Conditions, i.e. if and else commands, are very important when programming the Arduino. You can find out what you should consider for this in this practical tip.
Arduino conditions: The if command
Most important for conditions in Arduino programming is the if command.
- This command is relatively easy to use. The basic case "if (condition) {". Instead of "condition" write the respective condition.
- If you want to check whether one value is smaller than another, you can do this with "<". You can also use "" to check whether one value is larger than another. You can also use "> =" to check whether one value is greater than or equal to another. Finally, you can use "==" to check whether one value is exactly the same as another, or use "! =" If it does not.
- For example, an if command might look like this: "if (7> = 5) {". This condition would apply. After the curly brace, write the commands that should be executed if the condition applies. However, don't forget to add a closing brace at the end.
- If you still want to consider the case that the condition does not apply, you can add the "else {" command at the end. The commands within this command are executed if the condition is not met. Don't forget the brackets here, too.
Arduino: tips for if commands
To make programming even easier, there are a few tricks on how you can use if commands even more specifically.
- In this way, you can add an if statement within another if statement. One speaks of "nested if statements".
- There is also the "else-if statement". First you write a normal if command. After that, however, write "else if (...) {" and finally an else command. You can test several individual conditions that are to execute different commands one after the other.
- You can link several conditions with "&&". An example of this is the command "if (a <5 && b> = 17) {". Similarly, there is also an OR link. For example, the command "if (a <5 || b> = 17) {" applies if a is less than 5 or b is greater than or equal to 17.
Arduino: use switch commands
The switch command tests whether the value of a variable is equal to a certain value. Each value is called "case". At this point we have already defined a variable with the command »int day = 3;«. Now we want to insert a switch command.
- First, write the command "switch (day) {".
- Then the command "case 1:" is used to check whether "day" has the value 1. If this is the case, all commands below the case command (indented) are executed. If you want, you can add the "break;" command to these commands, which causes the switch command to be terminated as soon as the condition specified in the case command applies.
- Now you can add as many case commands as you want.
- If no condition applies, the commands that are (indented) under »default:« are executed.
In the next article we will give you an introduction to the programming language "Java".