Conditions, Loops, and Functions in ESP32 Programming
Conditions, loops, and functions are fundamental concepts in C++ programming. They allow an ESP32 to make decisions, repeat tasks, and organize code into reusable blocks.
For example, an ESP32 can use conditions to turn on an LED when a sensor detects motion, loops to monitor a sensor continuously, and functions to separate sensor readings from other operations.
By the end of this lesson, you will understand how to use these concepts in ESP32 projects with the Arduino framework.
1. Conditions in ESP32 Programming
Conditions allow a program to make decisions based on whether an expression is true or false.
For example:
- Turn on an LED when a button is pressed.
- Activate a buzzer when the temperature becomes too high.
- Display a message when a sensor value exceeds a threshold.
- Connect to Wi-Fi only when a condition is satisfied.
C++ provides several conditional statements, including if, if-else, else-if, and switch.
2. The if Statement
The if statement executes a block of code only when its condition is true.
Syntax
if (condition) { // Code executes when the condition is true }
Example
void setup() { Serial.begin(115200); int temperature = 35; if (temperature > 30) { Serial.println("Temperature is high!"); } } void loop() { }
Explanation
- The variable
temperaturestores the value35. - The condition
temperature > 30evaluates to true. - The message is printed to the Serial Monitor.
If the temperature were 25, the condition would be false, and the message would not be printed.
Important: The > operator checks whether one value is greater than another. Other comparison operators include:
| Operator | Meaning | Example |
|---|---|---|
== | Equal to | x == 10 |
!= | Not equal to | x != 10 |
> | Greater than | x > 10 |
< | Less than | x < 10 |
>= | Greater than or equal to | x >= 10 |
<= | Less than or equal to | x <= 10 |
Use == to compare values. A single = assigns a value to a variable.
3. The if-else Statement
The if-else statement selects between two alternatives.
Syntax
if (condition) { // Executes when the condition is true } else { // Executes when the condition is false }
Example: Temperature Monitoring
void setup() { Serial.begin(115200); int temperature = 28; if (temperature > 30) { Serial.println("Warning: High temperature!"); } else { Serial.println("Temperature is normal."); } } void loop() { }
If the temperature is greater than 30, the warning appears. Otherwise, the program displays that the temperature is normal.
This pattern is useful for sensor monitoring, security systems, and automation.
4. The else-if Ladder
Use an else-if ladder when a program must check multiple conditions.
Example: Temperature Categories
void setup() { Serial.begin(115200); int temperature = 38; if (temperature >= 40) { Serial.println("Critical temperature!"); } else if (temperature >= 30) { Serial.println("High temperature."); } else if (temperature >= 20) { Serial.println("Normal temperature."); } else { Serial.println("Low temperature."); } } void loop() { }
The program checks conditions from top to bottom. Once a condition is true, its block executes and the remaining branches are skipped.
Order matters. Check more restrictive or higher-priority conditions first. Otherwise, an earlier condition might match before a later condition is reached.
5. Nested if Statements
A nested if statement is an if statement placed inside another conditional block.
Example: Basic Access Check
void setup() { Serial.begin(115200); bool cardDetected = true; bool authorized = true; if (cardDetected) { Serial.println("Card detected."); if (authorized) { Serial.println("Access granted."); } else { Serial.println("Access denied."); } } else { Serial.println("No card detected."); } } void loop() { }
In this example, authorization is checked only after a card is detected.
Nested conditions are useful for RFID door locks, multi-step validation, and device control. For real security systems, authorization must be based on trustworthy checks rather than a hard-coded Boolean variable.
6. Logical Operators in Conditions
Logical operators combine or reverse conditions.
| Operator | Meaning | Example |
|---|---|---|
&& | Logical AND | temperature > 30 && humidity > 60 |
| ` | ` | |
! | Logical NOT | !authorized |
Example: Combined Conditions
void setup() { Serial.begin(115200); int temperature = 35; int humidity = 70; if (temperature > 30 && humidity > 60) { Serial.println("High temperature and humidity detected."); } if (temperature > 40 || humidity > 80) { Serial.println("Critical environmental condition."); } } void loop() { }
The first condition requires both comparisons to be true. The second condition requires at least one comparison to be true.
C++ also uses short-circuit evaluation: in an && expression, the second part is skipped if the first part is false. In an || expression, the second part is skipped if the first part is true.
7. The switch Statement
A switch statement selects a code block based on the value of an expression. It is useful when one variable can have several discrete values.
Syntax
switch (value) { case 1: // Code for value 1 break; case 2: // Code for value 2 break; default: // Code for other values break; }
The break statement exits the switch. Without it, execution can continue into the following cases.
Example: Device Modes
void setup() { Serial.begin(115200); int mode = 2; switch (mode) { case 1: Serial.println("Mode: Manual"); break; case 2: Serial.println("Mode: Automatic"); break; case 3: Serial.println("Mode: Maintenance"); break; default: Serial.println("Unknown mode."); break; } } void loop() { }
This approach is convenient for selecting operating modes in a smart home controller or an IoT device.
8. Loops in ESP32 Programming
Loops repeat a block of code. The ESP32 often needs to repeat tasks such as reading sensors, processing input, and controlling outputs.
C++ provides these main loop structures:
forwhiledo-while
The Arduino framework also repeatedly calls the loop() function. This means you can use a loop inside loop(), but unnecessary nested loops can prevent the device from responding promptly to other tasks.
9. The for Loop
A for loop is useful when you know how many times an operation should repeat.
Syntax
for (initialization; condition; update) { // Repeated code }
The three parts are:
- Initialization: Runs once at the beginning.
- Condition: Checked before each iteration.
- Update: Runs after each iteration.
Example: Print Numbers
void setup() { Serial.begin(115200); for (int i = 1; i <= 5; i++) { Serial.println(i); } } void loop() { }
Output:
1 2 3 4 5
The variable i starts at 1. The loop continues while i <= 5, and i++ increases the value by one after each iteration.
Example: Blink an LED Five Times
Connect an LED with a suitable current-limiting resistor to a supported GPIO and ground. The pin number below is an example; select a GPIO appropriate for your particular board.
const int LED_PIN = 2; void setup() { pinMode(LED_PIN, OUTPUT); for (int i = 0; i < 5; i++) { digitalWrite(LED_PIN, HIGH); delay(500); digitalWrite(LED_PIN, LOW); delay(500); } } void loop() { }
This code blinks the LED five times during setup, then leaves it off.
The delay() calls block normal execution while waiting. For more responsive applications, use a non-blocking timing approach with millis().
10. The while Loop
A while loop repeats as long as its condition remains true.
Syntax
while (condition) { // Repeated code }
Example
void setup() { Serial.begin(115200); int count = 1; while (count <= 5) { Serial.println(count); count++; } } void loop() { }
This program prints numbers from 1 to 5.
The variable count must change so that the condition eventually becomes false. If it never changes and the condition remains true, the loop may run indefinitely.
Example: Waiting for a Condition
const int BUTTON_PIN = 4; void setup() { Serial.begin(115200); pinMode(BUTTON_PIN, INPUT_PULLUP); } void loop() { while (digitalRead(BUTTON_PIN) == HIGH) { // Wait while the button is not pressed } Serial.println("Button pressed."); delay(200); }
With INPUT_PULLUP, the input is normally HIGH and becomes LOW when the button connects the GPIO to ground.
Caution: This example blocks while waiting. During that time, the rest of the sketch cannot run normally. For responsive projects, check the button once per pass through loop() instead of waiting inside a while loop.
11. The do-while Loop
A do-while loop checks its condition after executing the body. Therefore, the body runs at least once.
Syntax
do { // Executes at least once } while (condition);
Notice the semicolon after the while condition.
Example
void setup() { Serial.begin(115200); int number = 1; do { Serial.println(number); number++; } while (number <= 5); } void loop() { }
This example prints numbers from 1 to 5.
Difference Between while and do-while
| Feature | while | do-while |
|---|---|---|
| Condition checked | Before the body | After the body |
| Minimum executions | Zero | One |
| Useful for | Repeating while a condition holds | Running once before deciding whether to repeat |
12. The break Statement
The break statement exits the nearest loop immediately.
Example
void setup() { Serial.begin(115200); for (int i = 1; i <= 10; i++) { if (i == 6) { break; } Serial.println(i); } } void loop() { }
Output:
1 2 3 4 5
When i reaches 6, the loop stops.
In an ESP32 application, break can stop searching through a list once a matching sensor or device is found.
13. The continue Statement
The continue statement skips the remaining statements in the current iteration and proceeds to the next iteration.
Example
void setup() { Serial.begin(115200); for (int i = 1; i <= 5; i++) { if (i == 3) { continue; } Serial.println(i); } } void loop() { }
Output:
1 2 4 5
The value 3 is skipped.
Use continue when an iteration should be ignored, such as skipping an invalid sensor reading.
14. Nested Loops
A nested loop is a loop inside another loop. The inner loop runs for each iteration of the outer loop.
Example: Print a Pattern
void setup() { Serial.begin(115200); for (int row = 1; row <= 3; row++) { for (int column = 1; column <= 4; column++) { Serial.print("* "); } Serial.println(); } } void loop() { }
Output:
* * * * * * * * * * * *
Nested loops are useful for working with tables, matrices, and collections of readings. Be careful with deeply nested or long-running loops because they can make a microcontroller less responsive.
15. Functions in ESP32 Programming
A function is a named block of code that performs a specific task. Functions help divide a large program into smaller, understandable, and reusable parts.
For example, an IoT project might use separate functions to:
- Read a sensor.
- Check a threshold.
- Control an LED.
- Send data to a server.
- Display a status message.
Arduino sketches already use two special functions:
void setup() { // Runs once when the device starts } void loop() { // Runs repeatedly }
You can create additional functions for your own tasks.
16. Function Syntax
A typical function definition looks like this:
returnType functionName(parameters) { // Function body return value; }
The parts mean:
- Return type: The type of value returned, such as
int,float, orbool. Usevoidwhen no value is returned. - Function name: The identifier used to call the function.
- Parameters: Optional inputs supplied to the function.
- Function body: The statements that perform the task.
- Return statement: Sends a result back to the caller when the function has a non-
voidreturn type.
Example: A Function Without Parameters
void showMessage() { Serial.println("ESP32 is running!"); } void setup() { Serial.begin(115200); showMessage(); } void loop() { }
The showMessage() function prints a message. It is called from setup().
Because its return type is void, it does not return a value.
17. Functions with Parameters
Parameters allow you to pass information into a function.
Example
void printTemperature(int temperature) { Serial.print("Temperature: "); Serial.print(temperature); Serial.println(" C"); } void setup() { Serial.begin(115200); printTemperature(25); printTemperature(32); } void loop() { }
Output:
Temperature: 25 C Temperature: 32 C
The function accepts an integer parameter named temperature. Each call supplies a different value.
Parameters make functions reusable without duplicating the same code.
18. Functions That Return Values
Some functions calculate a result and return it to the caller.
Example: Add Two Numbers
int addNumbers(int a, int b) { return a + b; } void setup() { Serial.begin(115200); int result = addNumbers(10, 20); Serial.print("Result: "); Serial.println(result); } void loop() { }
Output:
Result: 30
The function accepts two integers and returns their sum. The returned value is stored in result.
The return type should match the kind of value being returned. For example, a function that returns a decimal measurement can use float.
Example: Convert an Analog Reading to a Percentage
int readingToPercent(int reading) { reading = constrain(reading, 0, 4095); return (reading * 100L) / 4095; } void setup() { Serial.begin(115200); int reading = 2048; int percentage = readingToPercent(reading); Serial.print("Reading percentage: "); Serial.print(percentage); Serial.println("%"); } void loop() { }
This example maps an input from 0–4095 to an approximate percentage. That range is common for the ESP32 Arduino analog-reading configuration, but the actual range depends on the board, ADC configuration, and hardware.
19. Function Prototypes
A function prototype declares a function's name, return type, and parameters before its definition.
Example
int multiplyNumbers(int a, int b); void setup() { Serial.begin(115200); Serial.println(multiplyNumbers(4, 5)); } void loop() { } int multiplyNumbers(int a, int b) { return a * b; }
The prototype tells the compiler how multiplyNumbers() can be called before the compiler reaches its definition.
The Arduino build system often generates prototypes automatically for .ino sketches. In ordinary C++ files and larger projects, explicit declarations in headers are common and help organize code.
20. Passing Arguments by Value
In a normal function call, parameters such as int are passed by value. The function receives a copy, so changing the parameter does not change the original variable.
Example
void changeValue(int number) { number = 100; } void setup() { Serial.begin(115200); int value = 10; changeValue(value); Serial.println(value); } void loop() { }
Output:
10
The variable number is a copy of value. Assigning 100 to number does not modify value.
21. Passing by Reference
A reference parameter allows a function to work directly with the original variable.
Example
void changeValue(int &number) { number = 100; } void setup() { Serial.begin(115200); int value = 10; changeValue(value); Serial.println(value); } void loop() { }
Output:
100
The & in int &number declares a reference parameter. Changes made through that reference affect the original variable.
References are useful when a function must update a value or when copying a larger object would be unnecessary.
22. The const Parameter
Use const when a function should read a parameter but must not modify it through that parameter.
void printReading(const int reading) { Serial.println(reading); } void setup() { Serial.begin(115200); const int sensorValue = 2500; printReading(sensorValue); } void loop() { }
For simple types passed by value, const mainly prevents accidental modification inside the function. For larger objects passed by reference, const references are especially useful because they avoid copying while preventing modification through that reference.
23. Local and Global Variables
Variables can be declared in different scopes.
Local Variable
A local variable is declared inside a function or block and is available only within that scope.
void showValue() { int number = 10; Serial.println(number); }
The variable number is local to showValue().
Global Variable
A global variable is declared outside functions and can be accessed by functions in the same scope.
int counter = 0; void increaseCounter() { counter++; } void setup() { Serial.begin(115200); increaseCounter(); Serial.println(counter); } void loop() { }
Global variables can be useful for shared state, such as a system mode or accumulated count. However, too many globals can make programs harder to understand and debug. Prefer local variables when shared access is unnecessary.
24. Combining Conditions, Loops, and Functions
These concepts become more powerful when used together.
Consider an ESP32 project that reads an analog sensor and controls an LED based on a threshold.
Example: Sensor Threshold Monitor
Connect a sensor with an analog output to a supported ADC-capable GPIO. This example uses GPIO 34 as an example input on a classic ESP32 board and GPIO 2 as an example LED pin. Pin availability differs across ESP32 variants and development boards.
const int SENSOR_PIN = 34; const int LED_PIN = 2; const int THRESHOLD = 2000; int readSensor() { return analogRead(SENSOR_PIN); } void controlLED(int sensorValue) { if (sensorValue > THRESHOLD) { digitalWrite(LED_PIN, HIGH); Serial.println("Threshold exceeded: LED ON"); } else { digitalWrite(LED_PIN, LOW); Serial.println("Normal reading: LED OFF"); } } void setup() { Serial.begin(115200); pinMode(SENSOR_PIN, INPUT); pinMode(LED_PIN, OUTPUT); } void loop() { int sensorValue = readSensor(); Serial.print("Sensor value: "); Serial.println(sensorValue); controlLED(sensorValue); delay(500); }
How It Works
setup()initializes serial communication and configures the pins.loop()repeatedly callsreadSensor().readSensor()returns the latest analog reading.controlLED()checks the reading against the threshold.- The LED turns on or off depending on the condition.
- The program waits 500 milliseconds and repeats.
This design separates sensor reading from output control, making the code easier to maintain and extend.
The threshold of 2000 is an example only. Calibrate it using actual sensor readings and the specific hardware.
25. Avoiding Blocking Loops with millis()
A long delay() or a loop that waits continuously can prevent your sketch from checking buttons, updating outputs, or performing other work promptly.
The millis() function returns the number of milliseconds since the ESP32 started running the program. It is commonly used for non-blocking timing.
Example: Blink an LED Without delay()
const int LED_PIN = 2; unsigned long previousMillis = 0; const unsigned long interval = 500; bool ledState = false; void setup() { pinMode(LED_PIN, OUTPUT); } void loop() { unsigned long currentMillis = millis(); if (currentMillis - previousMillis >= interval) { previousMillis = currentMillis; ledState = !ledState; digitalWrite(LED_PIN, ledState); } // Other tasks can run here. }
Explanation
previousMillisrecords the time of the last toggle.intervalspecifies the waiting period in milliseconds.- The condition checks whether enough time has elapsed.
- The LED state changes when the interval is reached.
- The loop remains free to perform other tasks between toggles.
Using unsigned time variables and subtraction in this pattern also works safely across the normal rollover of millis().
26. Common Mistakes
Mistake 1: Using = Instead of ==
Incorrect comparison:
if (value = 10) { Serial.println("Matched"); }
This assigns 10 to value; it does not compare the variable with 10.
Correct:
if (value == 10) { Serial.println("Matched"); }
Mistake 2: Creating an Infinite Loop Accidentally
Problem:
int count = 1; while (count <= 5) { Serial.println(count); }
The variable never changes, so the condition stays true.
Correction:
int count = 1; while (count <= 5) { Serial.println(count); count++; }
Mistake 3: Forgetting the break Statement
Without break, a switch case can continue into the next case.
Add break when you want a case to finish immediately, unless you intentionally want fall-through behavior.
Mistake 4: Returning the Wrong Type
If a function is declared to return int, it should return an appropriate integer value.
int getValue() { return 10; }
A void function does not return a value.
Mistake 5: Defining a Function but Never Calling It
Defining a function does not execute its body.
void showMessage() { Serial.println("Hello"); } void setup() { Serial.begin(115200); showMessage(); } void loop() { }
The call to showMessage() executes the function.
Mistake 6: Blocking the ESP32 for Too Long
Long delays and waiting loops can make a device unresponsive to other tasks in the sketch. Use millis()-based timing or an event-driven design when the application must remain responsive.
Mistake 7: Choosing an Invalid GPIO
Not every GPIO is suitable for every purpose. Some pins have boot-strapping functions, input-only limitations, or board-specific connections. Consult your ESP32 board's pinout before connecting components.
27. Best Practices
- Use
ifandelse-iffor clear, readable decision-making. - Use
switchwhen selecting among several discrete values. - Use
forfor a known number of repetitions. - Use
whilewhen repetition depends on a condition. - Use
do-whilewhen the body must execute at least once. - Keep functions focused on one task.
- Give functions descriptive names, such as
readTemperature()orcontrolMotor(). - Use parameters to share inputs instead of relying on unnecessary global variables.
- Choose the correct return type.
- Avoid long blocking loops in projects that must respond to sensors or buttons.
- Use Serial Monitor output to test and debug your logic.
- Keep hardware assumptions and threshold values appropriate for your actual board and sensors.
28. Practice Exercises
Try these exercises to strengthen your understanding.
Beginner
- Write an
if-elsestatement that checks whether a number is positive or non-positive. - Use a
forloop to print numbers from 1 to 20. - Write a function named
showWelcome()that prints a welcome message. - Create a function that accepts two integers and prints their sum.
Intermediate
- Use an
else-ifladder to classify a temperature as low, normal, high, or critical. - Write a
whileloop that counts down from 10 to 1. - Use
switchto select between three LED operating modes. - Write a function that returns the larger of two integers.
- Use a loop to read and print five analog sensor readings.
Advanced
- Build a sensor-threshold monitor using separate functions for reading the sensor and controlling an LED.
- Write a button-handling sketch that does not wait inside a blocking
whileloop. - Use
millis()to blink an LED while continuing to monitor another input. - Design a simple menu system using
switchand functions. - Create a function that accepts a sensor reading and returns
trueif the reading exceeds a chosen threshold.
Summary
Conditions allow an ESP32 to make decisions. Loops repeat operations, and functions divide a program into reusable blocks.
The main concepts covered in this lesson are:
if,if-else,else-if, andswitchfor decision-making.for,while, anddo-whilefor repetition.breakandcontinuefor controlling loop execution.- Functions with parameters and return values.
- Function prototypes, references, and variable scope.
- Combining conditions, loops, and functions in sensor-based applications.
- Using
millis()to build more responsive programs.
These concepts form the foundation for developing ESP32 projects such as sensor monitoring systems, smart lighting, automation controllers, and connected IoT devices.