Ugenz Academy/IoT Tutorial

Conditions Loops And Functions

15 min read2,895 words

Reading progress

Keep learning

Conditions, Loops and Functions

Now we move to one of the most important programming topics.

So far, you learned:

  • GPIO → how ESP32 interacts with hardware
  • Variables → how ESP32 stores information
  • Operators → how ESP32 calculates and compares information

Now we need to teach the ESP32:

"What should I do?"
"When should I do it?"
"How many times should I do it?"

That's where conditions, loops, and functions come in.


1. What Are Conditions?

A condition allows the ESP32 to make a decision.

For example:

Is temperature > 30°C? │ ┌───┴───┐ YES NO │ │ Fan ON Fan OFF

In programming, we commonly use:

if else else if

2. The if Statement

Basic syntax:

if (condition) { // code }

Example:

int temperature = 32; if (temperature > 30) { Serial.println("Temperature is high"); }

Because:

32 > 30

is true, the message is printed.


3. How if Works

Think of it as a question.

Condition │ Is it TRUE? / \ YES NO │ │ Execute Skip code code

Example:

if (temperature > 30) { digitalWrite(FAN_PIN, HIGH); }

Meaning:

If temperature is greater than 30°C, turn the fan on.


4. else

else tells the ESP32 what to do when the condition is false.

if (temperature > 30) { Serial.println("Hot"); } else { Serial.println("Normal"); }

For:

temperature = 32

Output:

Hot

For:

temperature = 25

Output:

Normal

5. Practical Fan Example

const int FAN_PIN = 25; float temperature = 32.5; void setup() { pinMode(FAN_PIN, OUTPUT); } void loop() { if (temperature > 30) { digitalWrite(FAN_PIN, HIGH); } else { digitalWrite(FAN_PIN, LOW); } }

Logic:

Temperature > 30? │ ┌───┴───┐ YES NO │ │ FAN ON FAN OFF

In a real project, temperature would come from a temperature sensor instead of being manually assigned.


6. else if

Sometimes you have multiple conditions.

Example:

if (temperature > 35) { Serial.println("Very Hot"); } else if (temperature > 30) { Serial.println("Hot"); } else if (temperature > 20) { Serial.println("Normal"); } else { Serial.println("Cold"); }

Suppose:

temperature = 32

The ESP32 checks:

32 > 35? → NO 32 > 30? → YES

So it prints:

Hot

Once one condition is satisfied, the remaining else if conditions are skipped.


7. Multiple Conditions with &&

Suppose you want the light to turn on only when:

  • It is dark
  • Someone is present

You can write:

if (dark && motionDetected) { digitalWrite(LIGHT_PIN, HIGH); }

Both must be true.

Dark? │ YES ↓ Motion? │ YES ↓ Light ON

8. Multiple Conditions with ||

Suppose you want an alarm if either:

  • Smoke is detected
  • Motion is detected
if (smokeDetected || motionDetected) { digitalWrite(BUZZER_PIN, HIGH); }

Only one needs to be true.

Smoke detected? │ ├── YES ──→ Alarm │ └── NO ↓ Motion detected? │ ├── YES → Alarm └── NO → Normal

9. Nested if

You can put an if inside another if.

Example:

if (securityArmed) { if (motionDetected) { Serial.println("Security Alert!"); } }

The ESP32 first checks:

Security armed?

If yes, then it checks:

Motion detected?

This is called a nested condition.


10. Conditions with Hardware

This is where programming becomes interesting.

Imagine:

PIR Sensor ↓ ESP32 GPIO ↓ motionDetected ↓ if ↓ Relay ↓ Light

Example:

bool motionDetected = digitalRead(PIR_PIN); if (motionDetected) { digitalWrite(LIGHT_PIN, HIGH); } else { digitalWrite(LIGHT_PIN, LOW); }

Now the ESP32 reacts to the physical world.


11. What Is a Loop?

A loop repeats a piece of code.

This is extremely important because an ESP32 often needs to continuously:

Read sensor ↓ Process data ↓ Control output ↓ Read sensor again ↓ Process data ↓ Control output ↓ ...

The main types you'll use are:

for while do...while

And Arduino/ESP32 programs have the special:

loop()

function, which itself runs repeatedly.


12. The loop() Function

Every normal Arduino-style ESP32 program has:

void setup() { } void loop() { }

setup() runs once.

loop() runs repeatedly.

Conceptually:

Power ON ↓ setup() ↓ loop() ↓ loop() ↓ loop() ↓ loop() ↓ ...

So:

void loop() { Serial.println("Hello"); delay(1000); }

prints:

Hello Hello Hello ...

13. Why loop() Is So Important

Most ESP32 projects are continuously monitoring something.

For example:

ESP32 │ ┌─────┼─────┐ ↓ ↓ ↓ PIR LDR DHT22 │ │ │ └─────┼─────┘ ↓ Process ↓ ┌─────┼─────┐ ↓ ↓ ↓ Light Fan Alarm

The loop() function repeatedly handles this process.


14. for Loop

A for loop is useful when you know how many times something should happen.

Basic syntax:

for (initialization; condition; update) { // code }

Example:

for (int i = 0; i < 5; i++) { Serial.println(i); }

Output:

0 1 2 3 4

15. Understanding the for Loop

Look at:

for (int i = 0; i < 5; i++)

It has three parts.

Part 1 — Initialization

int i = 0;

Start at 0.

Part 2 — Condition

i < 5

Continue while i is less than 5.

Part 3 — Update

i++

Increase i by 1 after each iteration.

So:

i = 0 → print i = 1 → print i = 2 → print i = 3 → print i = 4 → print i = 5 → stop

16. Practical for Loop

Suppose you want to blink an LED five times:

for (int i = 0; i < 5; i++) { digitalWrite(LED_PIN, HIGH); delay(500); digitalWrite(LED_PIN, LOW); delay(500); }

The loop runs five times.


17. while Loop

A while loop continues as long as a condition is true.

Syntax:

while (condition) { // code }

Example:

int count = 0; while (count < 5) { Serial.println(count); count++; }

Output:

0 1 2 3 4

18. while Loop Logic

Condition true? │ YES ↓ Execute code │ ↓ Check condition again │ └───────→

When the condition becomes false, the loop stops.


19. Infinite while Loop

Be careful.

This is dangerous:

int count = 0; while (count < 5) { Serial.println(count); }

Why?

Because count never changes.

Therefore:

count = 0 ↓ 0 < 5 → TRUE ↓ print ↓ 0 < 5 → TRUE ↓ print ↓ ...

It never ends.

This is called an infinite loop.


20. do...while

A do...while loop executes the code at least once before checking the condition.

Syntax:

do { // code } while (condition);

Example:

int count = 10; do { Serial.println(count); count++; } while (count < 5);

Even though:

10 < 5

is false, 10 is printed once.

Why?

Because the code executes first, then checks the condition.


21. while vs do...while

while

Checks first:

Check ↓ If true → Execute

do...while

Executes first:

Execute ↓ Check ↓ If true → Repeat

This difference is important.


22. break

break stops a loop immediately.

Example:

for (int i = 0; i < 10; i++) { if (i == 5) { break; } Serial.println(i); }

Output:

0 1 2 3 4

When:

i == 5

the loop stops.


23. continue

continue skips the current iteration and moves to the next one.

Example:

for (int i = 0; i < 5; i++) { if (i == 2) { continue; } Serial.println(i); }

Output:

0 1 3 4

The value 2 was skipped.


24. What Is a Function?

A function is a reusable block of code that performs a specific task.

Instead of writing the same code repeatedly:

Turn ON light Turn ON light Turn ON light

you can create:

void turnOnLight() { digitalWrite(LIGHT_PIN, HIGH); }

Then simply call:

turnOnLight();

25. Why Functions Are Useful

Functions make programs:

  • Easier to read
  • Easier to maintain
  • Easier to debug
  • More reusable
  • Better organized

Instead of one huge program:

1000 lines

you can organize it:

setup() loop() readTemperature() checkMotion() turnOnLight() sendData() connectWiFi()

This becomes much easier to understand.


26. Creating a Function

Basic syntax:

void functionName() { // code }

Example:

void sayHello() { Serial.println("Hello ESP32!"); }

Then:

void loop() { sayHello(); delay(1000); }

27. Functions with Parameters

A function can receive information.

Example:

void printTemperature(float temperature) { Serial.println(temperature); }

Call it:

printTemperature(28.5);

Here:

28.5 ↓ temperature parameter ↓ function

28. Multiple Parameters

You can pass multiple values.

void setRGB(int red, int green, int blue) { // control RGB LED }

Call:

setRGB(255, 0, 0);

This could represent:

Red = 255 Green = 0 Blue = 0

29. Functions That Return a Value

So far we've used:

void

void means the function doesn't return a value.

But a function can return something.

Example:

int add(int a, int b) { return a + b; }

Then:

int result = add(10, 20);

Now:

result = 30

30. Boolean Function

A function can return true or false.

Example:

bool isHot(float temperature) { if (temperature > 30) { return true; } return false; }

Then:

if (isHot(32)) { Serial.println("Hot!"); }

This makes complex logic easier to organize.


31. Practical ESP32 Function Example

Suppose you have a smart light.

const int LIGHT_PIN = 25; void turnLightOn() { digitalWrite(LIGHT_PIN, HIGH); } void turnLightOff() { digitalWrite(LIGHT_PIN, LOW); }

Now:

void loop() { turnLightOn(); delay(2000); turnLightOff(); delay(2000); }

The main program becomes easy to read.


32. Function for Reading a Sensor

Suppose you want a function that reads a sensor.

int readSensor() { int value = analogRead(34); return value; }

Then:

int sensorValue = readSensor(); Serial.println(sensorValue);

This separates sensor-reading logic from the rest of your program.


33. Functions + Conditions

Now combine them.

void controlLight(bool motionDetected) { if (motionDetected) { digitalWrite(LIGHT_PIN, HIGH); } else { digitalWrite(LIGHT_PIN, LOW); } }

Then:

bool motion = digitalRead(PIR_PIN); controlLight(motion);

This is much cleaner than putting everything inside loop().


34. Functions + Loops

Functions can also contain loops.

void blinkLED(int times) { for (int i = 0; i < times; i++) { digitalWrite(LED_PIN, HIGH); delay(500); digitalWrite(LED_PIN, LOW); delay(500); } }

Then:

blinkLED(3);

The LED blinks three times.

Or:

blinkLED(10);

It blinks ten times.


35. A Complete Example

Let's combine everything:

const int LED_PIN = 25; const int BUTTON_PIN = 18; void turnLEDOn() { digitalWrite(LED_PIN, HIGH); } void turnLEDOff() { digitalWrite(LED_PIN, LOW); } void setup() { Serial.begin(115200); pinMode(LED_PIN, OUTPUT); pinMode(BUTTON_PIN, INPUT_PULLUP); } void loop() { int buttonState = digitalRead(BUTTON_PIN); if (buttonState == LOW) { turnLEDOn(); Serial.println("Button pressed"); } else { turnLEDOff(); } delay(50); }

Let's understand the flow:

Button ↓ digitalRead() ↓ buttonState ↓ if / else ↓ Function ↓ LED

This is already a real embedded-system programming pattern.


36. A Smart Home Example

Imagine:

  • PIR detects motion
  • LDR detects darkness
  • Temperature sensor measures temperature
  • Relay controls light
  • Fan is controlled according to temperature

Your logic could be:

ESP32 │ ┌────────┼─────────┐ ↓ ↓ ↓ PIR LDR DHT22 │ │ │ ↓ ↓ ↓ Motion Light Temperature │ │ │ └────────┼─────────┘ ↓ Conditions ↓ ┌────────┼────────┐ ↓ ↓ ↓ Light Fan Alarm

Code could be organized into:

readSensors(); checkSecurity(); controlLight(); controlFan(); sendData();

This is exactly why functions become extremely important as your projects get larger.


37. setup() and loop() Are Functions

You have already been using functions without perhaps thinking about it.

void setup() { }

is a function.

And:

void loop() { }

is also a function.

The Arduino framework calls these functions for you.

Conceptually:

ESP32 starts ↓ setup() ↓ loop() ↓ loop() ↓ loop() ↓ ...

You don't normally call setup() yourself.


38. Don't Use delay() Everywhere

You will often see:

delay(1000);

It pauses the program for approximately one second.

For example:

digitalWrite(LED_PIN, HIGH); delay(1000); digitalWrite(LED_PIN, LOW);

But during that delay, your main code is not actively progressing.

For simple projects, delay() is fine.

For more advanced projects involving:

  • Wi-Fi
  • Web servers
  • Multiple sensors
  • Motors
  • Buttons
  • Real-time responses

you often want non-blocking timing using millis().

We'll study that in the later Timers, Interrupts and millis() topic.


39. Why Blocking Can Be a Problem

Imagine:

digitalWrite(LED_PIN, HIGH); delay(10000);

During those 10 seconds, your program is blocked from continuing through that code path.

If you need to:

Read PIR AND Read temperature AND Check button AND Handle Wi-Fi AND Update display

a long delay() can make the system feel unresponsive.

That's why professional embedded programs often use non-blocking techniques.


40. Decision + Loop + Function

These three concepts work together:

ESP32 │ LOOP │ ┌────────┼────────┐ ↓ ↓ ↓ Read Check Update Sensor Condition Output │ │ │ └────────┼────────┘ ↓ FUNCTION ↓ Perform Task ↓ LOOP ↺

This is the foundation of almost every ESP32 application.


41. Practical Example: Automatic Light

Let's create a simple logic system.

Requirements:

Turn the light ON when it is dark AND motion is detected.

Variables:

bool dark; bool motionDetected;

Condition:

if (dark && motionDetected) { turnLightOn(); } else { turnLightOff(); }

Function:

void turnLightOn() { digitalWrite(LIGHT_PIN, HIGH); }

Main loop:

void loop() { dark = readLightSensor(); motionDetected = digitalRead(PIR_PIN); if (dark && motionDetected) { turnLightOn(); } else { turnLightOff(); } }

Notice how the concepts connect:

Variables ↓ Sensor reading ↓ Condition ↓ Function ↓ Output ↓ Loop ↺

42. Common Beginner Mistakes

Mistake 1 — Using = instead of ==

Wrong:

if (buttonState = HIGH)

Usually you mean:

if (buttonState == HIGH)

Mistake 2 — Forgetting braces

Correct:

if (temperature > 30) { Serial.println("Hot"); }

Mistake 3 — Creating an infinite loop accidentally

Wrong:

while (count < 10) { Serial.println(count); }

because count never changes.


Mistake 4 — Forgetting to return a value

If you define:

int add(int a, int b) { }

the function is expected to return an int.

Correct:

int add(int a, int b) { return a + b; }

Mistake 5 — Putting everything in loop()

A giant loop() can become difficult to understand.

Instead:

readSensors(); processData(); controlDevices(); sendData();

is cleaner.


43. Quick Comparison

ConceptPurposeExample
ifMake a decisionif (temp > 30)
elseAlternativeelse
else ifMultiple choiceselse if (...)
forRepeat known number of timesfor (...)
whileRepeat while condition is truewhile (...)
do...whileExecute at least oncedo {...} while(...)
breakStop loopbreak;
continueSkip iterationcontinue;
FunctionReusable taskturnLightOn()
returnSend value from functionreturn value;

44. Key Points to Remember

  1. Conditions allow ESP32 to make decisions.
  2. if executes code when a condition is true.
  3. else handles the alternative.
  4. else if allows multiple conditions.
  5. && means AND.
  6. || means OR.
  7. ! means NOT.
  8. loop() repeats continuously in Arduino-style ESP32 programs.
  9. for is useful when you know the number of repetitions.
  10. while repeats while a condition remains true.
  11. do...while executes at least once.
  12. break exits a loop.
  13. continue skips an iteration.
  14. Functions organize reusable tasks.
  15. Functions can receive parameters.
  16. Functions can return values.
  17. setup() and loop() are functions.
  18. Long delay() calls can block program progress.
  19. Larger ESP32 projects should be divided into logical functions.
  20. Conditions + loops + functions = the core control structure of your ESP32 programs.

The Big Picture

Think of an ESP32 program like this:

START ↓ setup() ↓ loop() ↓ ┌──── Read Sensors │ ↓ Variables ↓ Conditions ↓ ┌─────┴─────┐ YES NO ↓ ↓ Function Function ↓ ↓ Output Output └─────┬─────┘ ↓ loop() ↺

In one sentence:

Conditions make decisions, loops repeat tasks, and functions organize the work into reusable blocks.

Keep learning. Keep building. Keep growing.

© 2026 Ugenz Academy