Switch Statement C/C++ Arduino Programming Practical use
Table of Contents
Description:
Switch Statement- Due to a lot of requests from my followers on YouTube Channel “Electronic Clinic” and Website to write an article about the Switch Statement with practical use. Today, I am writing this article about the Switch Statement and I will try to explain the maximum things so that you can use the switch-case statements in hardware-based projects as well.
There are so many articles about the switch statement, which only talk about software implementation. This article is unique in a sense as it focuses on the practical implementation of the Switch statement. In this article, I will practically use the Switch Statement in an Arduino based project Light meter. In this project, we will find the light intensity using the Switch case statements.
As you know in Arduino C/C++ programming is used, so I will stick with the C/C++ programming example. For the programming, I will use the Arduino IDE. If you have never used the Arduino IDE before, then I highly recommend reading my article on the Arduino IDE.
For the practical implementation, you will need a few electronic components,
- Arduino Uno
- LDR “Light Dependent Resistor”
- 10K resistor and finally
- Some jumper wires and a breadboard.
Without any further delay let’s get started!!!
Amazon Links:
*Disclosure: These are affiliate links. As an Amazon Associate I earn from qualifying purchases.
What is a Switch Statement?
Switch case statements in C/C++ programming are a substitute for long if statements that compare a variable to several integral values. In programming languages, a switch statement is a type of selection control mechanism used to allow the value of a variable or expression to change the control flow of program execution through search. Confusing?
Let’s make it simple, a switch statement is used to test the value stored in a variable by comparing it with multiple cases. Once the case match is found, a block of statements associated with that particular case is executed. Each case can consist of hundreds of statements and different functions.
Why to use Switch Case?
One of the most frequently asked questions related with the Switch Statement are
Why do we need a switch case?
Why to use a Switch Case?
As I said in the beginning a switch statement is basically a substitute of the if-else statement. There is one potential problem with the if-else statement which is, using many if-else statements increases the complexity, which makes the program hard to read, which even confuse the developer himself.
The switch case statement is used when we have multiple options and we need to perform a different task for each option. Let me make it more simple.
Let’s say you have a temperature sensor and you are told to monitor different temperatures like
Normal temperature, hot, very hot, and extreme temperature. This thing can be easily done with the switch case statement. You can use 4 cases. The temperature value can be compared with the 4 cases. I will practically demonstrate this for an LDR in a minute.
Syntax of Switch Statement:
When it comes to programming, anything we write in the program has certain syntax.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
Switch ( A variable or an integer expression) { Case constant-1: // statements Break; Case constant-2: // statements Break; Case constant-3: // statements Break; Case constant-n: // statements Break; Default: //statements } |
The rules you need to take care of while using the switch statement:
- An expression must always execute to a result.
- Case labels used in the programming must be unique. Duplicate case values are not allowed.
- Every case label used must end with a colon :.
- Each case should include the break keyword at the end, this terminates the switch, and the flow of control jumps to the next line following the switch statement.
- There can be only one default label
- Unlike the if-else statements we can nest multiple switch statements.
Flowchart of Switch Statement:
Basic switch statement program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
// Switch Statement #include <stdio.h> // header file int main() // main function { int num = 8; // currently 8 is stored in the variable num which is of the type integer. //The value stored in variable num will be compared with all the cases. switch (num) { case 7: printf("Value is 7"); break; case 8: printf("Value is 8"); break; case 9: printf("Value is 9"); break; default: printf("Out of range"); break; } return 0; } |
This program will output “Value is 8”.
So, now that we have covered the basics things, now it’s time to make a practical project based on the switch statement.
Light meter Circuit Diagram:
As you can see the circuit diagram is really simple. An LDR”Light Dependent Resistor” is connected in series with a 10k ohm resistor. The LDR and 10k ohm resistor together makes a voltage divider circuit. This voltage divider circuit is connected with the Arduino’s 5 volts and GND. A wire from the middle is connected with the Arduino’s analog pin A1. The voltage available on the A1 pin of the Arduino changes as the light intensity changes. This change in the voltage is read by the A1 pin. These different voltage values represents different light intensity levels. Let’s have a look at the Arduino programming.
Switch statement based Light meter Arduino Programming:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
int ldr = A1; int ldr_data = 0; int maxvalue = 285; int minvalue = 20; void setup() { Serial.begin(9600); pinMode(ldr, INPUT); } void loop() { ldr_data = analogRead(ldr); // Serial.print("ldr value"); // Serial.println(ldr_data); int ldrrange = map( ldr_data , minvalue, maxvalue, 0 , 3 ) ; //Serial.println(ldrrange); //delay(500); switch( ldrrange) { case 0: Serial.println("Dark "); break; case 1: Serial.println("Dim"); break; case 2: Serial.println("Medium "); break; case 3: Serial.println("Bright "); break; } delay(200); } |
Program explanation:
int ldr = A1;
First, I started off by defining a pin for the LDR. The middle wire coming from the LDR circuit is connected with the Arduino’s Analog pin A1.
int ldr_data = 0;
then I defined a variable ldr_data for storing the values coming from the ldr circuit.
And finally I defined the maximum and minimum values which are given below.
int maxvalue = 285;
int minvalue = 20;
void setup()
{
Serial.begin(9600);
I activated the serial communication using the Serial.begin() function. This way I can send values to the serial monitor. and finally, I set the ldr sensor as the input. using the pinMode() function.
pinMode(ldr, INPUT);
}
void loop()
{
ldr_data = analogRead(ldr);
using the analogRead() I read the analog pin A1 which is named ldr and stored the value in variable ldr_data.
// Serial.print(“ldr value”);
// Serial.println(ldr_data);
int ldrrange = map( ldr_data , minvalue, maxvalue, 0 , 3 ) ;
then using the map() function I limit the range from 0 to 3.
As the light changes I will get values from 0 to 3. The value can be 0, 1, 2, or 3.
These values will be stored in the variable ldrrange, so at this point I can use the if else statements or I can use the switch case statements. As this article is about the switch case statement so I am going to use it.
//Serial.println(ldrrange);
//delay(500);
Now, the rest of the programs is pretty straight forward, the value stored in ldrrange is compared with the cases, let’s say if the value in ldrrange is 3 then case 3 will be executed and it will print medium on the Serial monitor.
switch( ldrrange)
{
case 0:
Serial.println(“Dark “);
break;
case 1:
Serial.println(“Dim”);
break;
case 2:
Serial.println(“Medium “);
break;
case 3:
Serial.println(“Bright “);
break;
}
delay(200);
}
Download Proteus simulation of the Light Meter based on the Switch Statement.
Download: Proteus simulation
I checked the above program in the Proteus simulation software and it worked the way I wanted it to work. You can download this simulation file for the practice.
Now let’s study different points. What will happen if we don’t use the break statement in cases? Let’s check.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
int ldr = A1; int ldr_data = 0; int maxvalue = 285; int minvalue = 20; void setup() { Serial.begin(9600); pinMode(ldr, INPUT); } void loop() { ldr_data = analogRead(ldr); // Serial.print("ldr value"); // Serial.println(ldr_data); int ldrrange = map( ldr_data , minvalue, maxvalue, 0 , 3 ) ; //Serial.println(ldrrange); //delay(500); switch( ldrrange) { case 0: Serial.println("Dark "); case 1: Serial.println("Dim"); case 2: Serial.println("Medium "); case 3: Serial.println("Bright "); } delay(200); } |
As you can see this is the same program but without the break statements.
As you can see in the picture above, all the cases are executed one by one as there is no break statement to terminate the execution or flow. Download the Proteus simulation file and play with the code. Add the default case and check what happens?
So, this is how easily we can use the switch statement in Arduino programming and make some cool projects. The switch case statements can be used in advanced level projects for making menus. I hope this article helps you.
Let me know in a comment, in which project you are going to use the switch statement? For more basic and advanced level projects visit my YouTube channel “Electronic Clinic”.