Conditional statements (if-else, switch-case) in Arduino code

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.

The if-else statement

The 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
}
If-Else syntax

Example: Controlling multiple LEDs

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.

Hardware required

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

Circuit connections

  1. Connect the potentiometer:

    1. Connect one end of the potentiometer to 5V on the Arduino board.

    2. Connect the other end of the potentiometer to GND on the Arduino board.

    3. Connect the wiper (middle terminal) of the potentiometer to the analog pin A0 on the Arduino board.

  2. Connect the LEDs with resistors:

    1. Connect the first LED's anode (longer leg) to digital pin 9 on the Arduino board through a 220-ohm resistor.

    2. Connect the first LED's cathode (shorter leg) to GND on the Arduino board.

    3. Similarly, connect the second LED’s anode to digital pin 10 through a 220-ohm resistor and the cathode to GND.

    4. 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.

Circuit diagram

Circuit diagram
Circuit diagram

Code

The code used for this example is:

const int potPin = A0; // Connect potentiometer to analog pin A0
const int led1 = 9; // LED connected to pin 9
const int led2 = 10; // LED connected to pin 10
const int led3 = 11; // LED connected to pin 11
void 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);
}
}
Code for controlling multiple LEDs

Upload the code

  1. Connect your Arduino board to the computer using the USB cable.

  2. Open the Arduino IDE and copy the code into a new sketch.

  3. Select the correct board and port under the "Tools" menu.

  4. Click on the checkmark icon (✓) to verify the error code. Fix any errors that appear.

  5. Click on the right-arrow icon (➔) to upload the code to your Arduino board.

Observations

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.

The switch-case statement

The 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 value1
break;
case value2:
// Code to be executed if variable matches value2
break;
// Add more cases as needed
default:
// Code to be executed if no case matches the variable
}
switch-case syntax

Example: Traffic light control

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.

Hardware required

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

Circuit connections

  1. Connect the LEDs with resistors:

    1. Connect the Red LED's anode (longer leg) to digital pin 9 on the Arduino board through a 220-ohm resistor.

    2. Connect the Yellow LED's anode (longer leg) to digital pin 10 on the Arduino board through a 220-ohm resistor.

    3. Connect the Green LED's anode (longer leg) to digital pin 11 on the Arduino board through a 220-ohm resistor.

    4. Connect each LED's cathode (shorter leg) to GND on the Arduino board.

  2. Connect the push-button switch:

    1. Connect one push-button terminal to digital pin 2 on the Arduino board.

    2. Connect the other terminal of the push-button to GND on the Arduino board.

    3. 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.

Circuit diagram

Circuit diagram
Circuit diagram

Code

const int redPin = 9; // Red LED connected to pin 9
const int yellowPin = 10; // Yellow LED connected to pin 10
const int greenPin = 11; // Green LED connected to pin 11
const int buttonPin = 2; // Push-button connected to pin 2
// Define traffic light states
enum 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 pressed
if (digitalRead(buttonPin) == LOW) {
// Change the traffic light state based on the current state
switch (currentLightState) {
case RED:
currentLightState = GREEN;
break;
case GREEN:
currentLightState = YELLOW;
break;
case YELLOW:
currentLightState = RED;
break;
}
// Update the traffic light according to the new state
updateTrafficLight();
// Wait to avoid multiple state changes due to button debounce
delay(500);
}
}
// Function to update the traffic light based on the current state
void 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;
}
}

Upload the code

  1. Connect your Arduino board to the computer using the USB cable.

  2. Open the Arduino IDE and copy the code into a new sketch.

  3. Select the correct board and port under the "Tools" menu.

  4. Click on the checkmark icon (✓) to verify the error code. Fix any errors that appear.

  5. Click on the right-arrow icon (➔) to upload the code to your Arduino board.

Observations

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.

Critical differences between if-else and switch-case

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

Conclusion

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.

Copyright ©2024 Educative, Inc. All rights reserved