Arduino programming involves using conditional statements to control the flow of code execution based on specific conditions. Two common conditional statements used in Arduino are the if-else
and switch-case
. These statements allow the Arduino to make decisions and perform different actions based on the values of variables or sensors.
if-else
statementThe if-else
statement is a fundamental conditional statement that allows you to execute different blocks of code depending on whether a specific condition is true or false. It follows a simple structure:
if (condition) {// Code to be executed if the condition is true} else {// Code to be executed if the condition is false}
Suppose you have three LEDs connected to pins 9, 10, and 11, and you want to control their state based on the value of a single sensor.
To implement the circuit for the given Arduino code, you’ll need the following components:
Arduino board (e.g., Arduino Uno)
A potentiometer (variable resistor)
Three LEDs (different colors if possible)
Three 220-ohm resistors (for current limiting the LEDs)
Breadboard and jumper wires
Connect the potentiometer:
Connect one end of the potentiometer to 5V on the Arduino board.
Connect the other end of the potentiometer to GND on the Arduino board.
Connect the wiper (middle terminal) of the potentiometer to the analog pin A0 on the Arduino board.
Connect the LEDs with resistors:
Connect the first LED's anode (longer leg) to digital pin 9 on the Arduino board through a 220-ohm resistor.
Connect the first LED's cathode (shorter leg) to GND on the Arduino board.
Similarly, connect the second LED’s anode to digital pin 10 through a 220-ohm resistor and the cathode to GND.
Connect the third LED’s anode to digital pin 11 through a 220-ohm resistor and the cathode to GND.
Note: Ensure the potentiometer is connected as a voltage divider between 5V and GND, and the middle terminal (wiper) is connected to analog pin A0. The LEDs should be connected with the correct polarity, where the longer leg (anode) connects to the Arduino pin through a resistor, and the shorter leg (cathode) connects to GND.
The code used for this example is:
const int potPin = A0; // Connect potentiometer to analog pin A0const int led1 = 9; // LED connected to pin 9const int led2 = 10; // LED connected to pin 10const int led3 = 11; // LED connected to pin 11void setup() {pinMode(led1, OUTPUT);pinMode(led2, OUTPUT);pinMode(led3, OUTPUT);}void loop() {int sensorValue = analogRead(potPin);if (sensorValue < 341) {digitalWrite(led1, HIGH);digitalWrite(led2, LOW);digitalWrite(led3, LOW);} else if (sensorValue < 682) {digitalWrite(led1, LOW);digitalWrite(led2, HIGH);digitalWrite(led3, LOW);} else {digitalWrite(led1, LOW);digitalWrite(led2, LOW);digitalWrite(led3, HIGH);}}
Connect your Arduino board to the computer using the USB cable.
Open the Arduino IDE and copy the code into a new sketch.
Select the correct board and port under the "Tools" menu.
Click on the checkmark icon (✓) to verify the error code. Fix any errors that appear.
Click on the right-arrow icon (➔) to upload the code to your Arduino board.
When you run the Arduino code with this circuit, the three LEDs will respond to the analog value read from the potentiometer. The LED1 (Red) will turn on when the potentiometer value is less than 341, LED2 (Green) will turn on when the potentiometer value is between 341 and 681, and LED3 (Blue) will turn on when the potentiometer value is greater than or equal to 682. The intensity of the LEDs will vary depending on the potentiometer position.
switch-case
statementThe switch-case
statement is applicable when you have multiple conditions to check against a single variable. It provides a more organized and concise way to handle multiple options. The basic structure of the switch-case statement is as follows:
switch (variable) {case value1:// Code to be executed if variable matches value1break;case value2:// Code to be executed if variable matches value2break;// Add more cases as neededdefault:// Code to be executed if no case matches the variable}
In this example, we will simulate a simple traffic light system using three LEDs representing red, yellow, and green lights. We will use a push-button to change the traffic light state.
To implement the circuit for the given Arduino code that simulates a traffic light control system, you’ll need the following components:
Arduino board (e.g., Arduino Uno)
Three LEDs (Red, Yellow, and Green)
Three 220-ohm resistors (for current limiting the LEDs)
A push-button switch
A 10k-ohm resistor (for pull-up on the button)
Breadboard and jumper wires
Connect the LEDs with resistors:
Connect the Red LED's anode (longer leg) to digital pin 9 on the Arduino board through a 220-ohm resistor.
Connect the Yellow LED's anode (longer leg) to digital pin 10 on the Arduino board through a 220-ohm resistor.
Connect the Green LED's anode (longer leg) to digital pin 11 on the Arduino board through a 220-ohm resistor.
Connect each LED's cathode (shorter leg) to GND on the Arduino board.
Connect the push-button switch:
Connect one push-button terminal to digital pin 2 on the Arduino board.
Connect the other terminal of the push-button to GND on the Arduino board.
Connect a 10k-ohm resistor between digital pin 2 and 5V on the Arduino board (this is the pull-up resistor).
Note: The LEDs should be connected with the correct polarity, where the longer leg (anode) connects to the Arduino pin through a resistor, and the shorter leg (cathode) connects to GND.
const int redPin = 9; // Red LED connected to pin 9const int yellowPin = 10; // Yellow LED connected to pin 10const int greenPin = 11; // Green LED connected to pin 11const int buttonPin = 2; // Push-button connected to pin 2// Define traffic light statesenum TrafficLightState {RED,GREEN,YELLOW,};TrafficLightState currentLightState = RED;void setup() {pinMode(redPin, OUTPUT);pinMode(yellowPin, OUTPUT);pinMode(greenPin, OUTPUT);pinMode(buttonPin, INPUT_PULLUP);updateTrafficLight();}void loop() {// Check if the button is pressedif (digitalRead(buttonPin) == LOW) {// Change the traffic light state based on the current stateswitch (currentLightState) {case RED:currentLightState = GREEN;break;case GREEN:currentLightState = YELLOW;break;case YELLOW:currentLightState = RED;break;}// Update the traffic light according to the new stateupdateTrafficLight();// Wait to avoid multiple state changes due to button debouncedelay(500);}}// Function to update the traffic light based on the current statevoid updateTrafficLight() {digitalWrite(redPin, LOW);digitalWrite(yellowPin, LOW);digitalWrite(greenPin, LOW);switch (currentLightState) {case RED:digitalWrite(redPin, HIGH);break;case GREEN:digitalWrite(greenPin, HIGH);break;case YELLOW:digitalWrite(yellowPin, HIGH);break;}}
Connect your Arduino board to the computer using the USB cable.
Open the Arduino IDE and copy the code into a new sketch.
Select the correct board and port under the "Tools" menu.
Click on the checkmark icon (✓) to verify the error code. Fix any errors that appear.
Click on the right-arrow icon (➔) to upload the code to your Arduino board.
The three LEDs will mimic a traffic light sequence when you run the Arduino code with this circuit. Pressing the push button will cause the traffic light to change its state in a cyclic manner: RED → GREEN → YELLOW → RED. The cycle will repeat each time you press the button. The delay(500) in the code ensures a delay between state changes to avoid multiple state changes due to button debounce.
Feature | if-else statement | switch-case statement |
Usage | Ideal for simple condition checking where only one condition needs to be evaluated | More suitable when multiple discrete cases are based on a single variable |
Comparison | Allows you to use relational operators (e.g., ==, >, <) to check conditions | Only checks if a variable matches specific constant values |
Flexibility | Can handle complex conditions using logical operators (e.g., &&, ||) | Only handles exact matches and does not support complex conditions |
Readability | Pretty readable | Provides a more precise and concise way to handle multiple options, enhancing code readability |
Conditional statements, such as the if-else
and switch-case
, are essential tools in Arduino programming. They enable you to create responsive and dynamic projects by making decisions based on changing conditions or user input. Understanding these statements and when to use them will empower you to write more efficient and organized Arduino code.