Arduino Basic Tutorial

switch statement in arduino programming

switch statement in Arduino:

switch statement in Arduino-In my previous article, we learned about if and else if statements. Which is used for condition checking and This is a valid way to check the multiple conditions, but in this article, we will learn another more elegant, comfortable, and easy way to do the same: using the switch case statement.

Like if, switch case controls the flow of programs, allowing programmers to specify different codes to run under different conditions. Specifically, the switch operator compares the value of a variable to the values specified in case statements. When a case statement is found that has the same value as a variable, the case code is run.

A switch statement in Arduino is a special form of multiple–alternative decision making i.e when multiple-choice possibilities are based on a single value the switch statement is the best choice. Actually switch statement is a more efficient way of representing a nested-if statement. This statement is used to transfer control to a selected case of any one of the several indicated cases depending on the value of the switch expression

general syntax of switch statement in Arduino:

expression is compared for equality to each case label. If expression equals a particular label value, the statements in this case are executed until the next break. If there is no match and you have used the optional default: case, the statements of this case are executed. Without the default: case, nothing is done. label must be a value, not a character, not string.

Flowchart of Arduino switch statement:

switch statement in arduino

Break Statement in Arduino:

The ‘break’ statement is used to exit from the body the switch statement (or loop structure). After executing this statement, execution control is transferred to the statement that comes immediately after the switch statement (or loop structure).

In the switch statement, the break statement is normally used at the end of the statement in each case. If all break statements are omitted from the switch statement, then the statement of all the remaining cases that come after the matched case are also executed in sequential order.

Example: how to use switch case statement in Arduino programming:


switch statement in arduino

switch statement in arduino

switch statement in arduino

When you have comparison intervals, if…else is more convenient because you can use < and > whereas in switch…case…break you cannot.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button