Switch Case 21
Switch Case 21
To show the application of switch case in Arduino programming for the following example.
Assume that six LEDs have been connected to digital input/output pins of arduino board
from 2 to 7. Use for switch case statement to read the values from serial monitor from "A
to F" and turn on the respective LED from pins 2 to 7
Code:
int n=0;
MARWADI UNIVERSITY
DEPARTMENT OF INFORMATION AND
COMMUNICATION TECHNOLOGY
Foundation Skills in Sensor Interfacing (01CT1103)
void setup()
{
Serial.begin(9600);
pinMode(2,OUTPUT);
pinMode(3,OUTPUT);
pinMode(4,OUTPUT);
pinMode(5,OUTPUT);
pinMode(6,OUTPUT);
pinMode(7,OUTPUT);
}
void loop()
{
if (Serial.available()>0)
{
n=Serial.read();
switch(n)
{ case'a' : digitalWrite(1,HIGH);
delay(1000);
digitalWrite(1, LOW);
delay(1000);
break;
case'b' : digitalWrite(2,HIGH);
delay(1000);
digitalWrite(2,HIGH);
delay(1000);
break;
case'c' : digitalWrite(3,HIGH);
delay(1000);
digitalWrite(3,HIGH);
delay(1000);
break;
case'd' : digitalWrite(4,HIGH);
delay(1000);
digitalWrite(4,HIGH);
delay(1000);
break;
MARWADI UNIVERSITY
DEPARTMENT OF INFORMATION AND
COMMUNICATION TECHNOLOGY
Foundation Skills in Sensor Interfacing (01CT1103)
case'e' : digitalWrite(5,HIGH);
delay(1000);
digitalWrite(5,HIGH);
delay(1000);
break;
case'f' : digitalWrite(6,HIGH);
delay(1000);
digitalWrite(6,HIGH);
delay(1000);
break;
}
}
}
Application: They save you from having to write tons of chained if else
statements. The Arduino switch statement takes a single expression. Multiple
Arduino case statements act on the expression. If the expression evaluates to
3 then an action 1 is executed.
Conclusion: The switch case controls the flow of the program by executing the
code in various cases. A switch statement compares a particular value of a
variable with statements in other cases