Switch case in Arduino

ArduinoArduino BoardsArduino IDEArduino Programming Language

Switch case in Arduino is just like the switch case in C language. For those who are unaware of switch case, it is a more compact way of writing multiple if statements, when they concern the value of a variable.

Syntax

switch (var) {
   case value1:
      // statements for value1
      break;
   case value2:
      // statements for value2
      break;
.
.
.
   default:
      // statements for default value
      break;
}

var is the variable whose different values we are checking. If its value is equal to value1, then the statements for value1 will be executed. If its value is equal to value2, then the statements for value2 will be executed, and so on. If the value is not equal to any values listed, then the statements corresponding to the default value will be executed. If you don’t add the break statement after each case, then all the cases following it will be executed, till the first break is encountered.

Example

void setup() {
   // put your setup code here, to run once:
   Serial.begin(9600);
   Serial.println();

   while(!Serial.available()){
      Serial.print('.');
      delay(500);
   }

   int a = Serial.parseInt();
   Serial.print("Serial value received is "); Serial.println(a);
   switch(a){
      case 1:
         Serial.println("Value 1 received");
         break;

      case 2:
         Serial.println("Value 2 received");
         break;

      case 3:
         Serial.println("Value 3 received");
         break;

      default:
         Serial.println("Value outside 1,2,3 received");
         break;
   }
}

void loop() {
   // put your main code here, to run repeatedly:
}

As you can see, we take one integer from the user (Serial.parseInt()), and print different values depending on the value of the input.

Output

The Serial Monitor Output is shown below −


raja
Published on 29-May-2021 13:29:17
Advertisements