Ugenz Academy/IoT Tutorial

Functions And Code Reusability

17 min read3,270 words

Reading progress

Keep learning

Functions and Code Reusability in ESP32 Programming

Functions are one of the most important concepts in C++ programming for ESP32. They allow you to divide a large program into smaller, reusable, and organized blocks of code.

When developing IoT projects, you may need to read sensors, control LEDs, operate motors, check button inputs, and send data over Wi-Fi. Writing all these operations inside a single loop() function can make the program difficult to understand and maintain.

By using functions, you can separate each task into a meaningful block and reuse it whenever needed.

In this lesson, you will learn how to create functions, pass arguments, return values, organize code into multiple files, and apply code reusability in practical ESP32 projects.

1. What Is a Function?

A function is a named block of code designed to perform a particular task.

For example, an ESP32 project might contain functions such as:

  • readTemperature() — reads a temperature sensor.
  • turnOnLED() — switches on an LED.
  • calculateAverage() — calculates an average value.
  • checkPassword() — checks whether an entered password matches an expected value.
  • sendSensorData() — prepares sensor data for transmission.

Instead of writing the same instructions repeatedly, you can write a function once and call it whenever required.

Basic Example

void showMessage() { Serial.println("Welcome to ESP32 Programming!"); } void setup() { Serial.begin(115200); showMessage(); } void loop() { }

Explanation

  1. void specifies that the function does not return a value.
  2. showMessage is the function name.
  3. The parentheses () contain the parameter list, which is empty here.
  4. The curly braces {} contain the function body.
  5. showMessage(); calls the function and executes its instructions.

The message is printed once because the function is called from setup().

2. Why Is Code Reusability Important?

Code reusability means writing code in a way that allows the same logic to be used in multiple places without unnecessary duplication.

Consider an application that needs to display the same status message several times.

Without a function:

void setup() { Serial.begin(115200); Serial.println("ESP32 is ready."); Serial.println("ESP32 is ready."); Serial.println("ESP32 is ready."); } void loop() { }

With a reusable function:

void showReadyMessage() { Serial.println("ESP32 is ready."); } void setup() { Serial.begin(115200); showReadyMessage(); showReadyMessage(); showReadyMessage(); } void loop() { }

Both examples produce the same output, but the second makes the repeated task easier to manage.

If the message changes, you only need to update the function.

Benefits of Code Reusability

  • Less duplication: The same logic does not need to be rewritten.
  • Better readability: Function names explain what the code does.
  • Easier maintenance: A change can often be made in one place.
  • Simpler testing: Individual functions can be tested separately.
  • Improved organization: Large programs can be divided into smaller tasks.
  • Easier expansion: New features can use existing functions.

3. Function Declaration, Definition, and Calling

Three terms are important when working with functions.

Function Declaration

A declaration, often called a prototype, tells the compiler a function's name, return type, and parameters.

int addNumbers(int a, int b);

Function Definition

The definition contains the actual implementation.

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

Function Call

A call executes the function.

int result = addNumbers(10, 20);

The returned value is stored in result.

Complete Example

int addNumbers(int a, int b); void setup() { Serial.begin(115200); int result = addNumbers(10, 20); Serial.print("Sum: "); Serial.println(result); } void loop() { } int addNumbers(int a, int b) { return a + b; }

Output:

Sum: 30

A prototype is particularly useful when a function is defined after the code that calls it or when functions are organized into separate files.

Arduino .ino sketches often receive automatically generated function prototypes during compilation, but normal C++ source files do not generally rely on that Arduino-specific behavior.

4. Functions Without Parameters

A function does not always need input values.

Example

void turnOnLED() { digitalWrite(2, HIGH); } void setup() { pinMode(2, OUTPUT); turnOnLED(); } void loop() { }

The turnOnLED() function always performs the same operation.

This is useful when a task does not require any additional information.

Hardware note: GPIO 2 is only an example. Check your development board's pinout before selecting an LED pin.

5. Functions with Parameters

Parameters allow a function to accept different inputs each time it is called.

Example: Control LED State

const int LED_PIN = 2; void setLED(bool state) { digitalWrite(LED_PIN, state ? HIGH : LOW); } void setup() { pinMode(LED_PIN, OUTPUT); setLED(true); delay(1000); setLED(false); } void loop() { }

Here, state is a Boolean parameter.

  • setLED(true) turns the LED on.
  • setLED(false) turns the LED off.

The function is reusable because it supports both operations through one implementation.

6. Functions with Multiple Parameters

A function can accept more than one parameter.

Example: Configure an LED

void blinkLED(int pin, int delayTime) { digitalWrite(pin, HIGH); delay(delayTime); digitalWrite(pin, LOW); delay(delayTime); } void setup() { pinMode(2, OUTPUT); pinMode(4, OUTPUT); } void loop() { blinkLED(2, 500); blinkLED(4, 200); }

The same function is used for two different pins and timing values.

The first LED uses a 500-millisecond interval, while the second uses 200 milliseconds.

This example demonstrates reuse, but delay() blocks normal execution. For applications that must monitor sensors or handle several devices at once, a non-blocking design is usually preferable.

7. Functions That Return Values

A function can return a calculated value to the calling code.

Example: Calculate an Average

float calculateAverage(int first, int second, int third) { return (first + second + third) / 3.0f; } void setup() { Serial.begin(115200); float average = calculateAverage(20, 25, 30); Serial.print("Average: "); Serial.println(average); } void loop() { }

Output:

Average: 25.00

The return type is float because the average can contain a decimal component.

The return statement sends the result back to the caller.

Common return types include:

Return typePurpose
voidDoes not return a value
intReturns an integer
floatReturns a floating-point value
boolReturns true or false
charReturns a character

Choose a return type appropriate for the result.

8. Reusing Sensor-Reading Functions

Sensor-reading functions are especially useful in IoT projects because the same reading operation may be needed in several parts of an application.

Example: Read an Analog Sensor

Connect an analog-output sensor to a suitable ADC input. GPIO 34 is used as an example for a classic ESP32.

const int SENSOR_PIN = 34; int readSensor() { return analogRead(SENSOR_PIN); } void setup() { Serial.begin(115200); } void loop() { int sensorValue = readSensor(); Serial.print("Sensor reading: "); Serial.println(sensorValue); delay(1000); }

The readSensor() function hides the hardware-reading instruction behind a meaningful name.

The function can be called from other parts of the application whenever a reading is required.

The analog range and available ADC pins vary by ESP32 model and configuration. Calibrate the sensor using your actual hardware.

9. Separating Sensor Reading from Decision-Making

A reusable design separates reading a sensor from deciding what to do with the result.

Example: Threshold-Based LED Control

const int SENSOR_PIN = 34; const int LED_PIN = 2; const int THRESHOLD = 2000; int readSensor() { return analogRead(SENSOR_PIN); } bool isThresholdExceeded(int value) { return value > THRESHOLD; } void updateLED(bool alarm) { digitalWrite(LED_PIN, alarm ? HIGH : LOW); } void setup() { Serial.begin(115200); pinMode(SENSOR_PIN, INPUT); pinMode(LED_PIN, OUTPUT); } void loop() { int reading = readSensor(); bool alarm = isThresholdExceeded(reading); updateLED(alarm); Serial.print("Reading: "); Serial.print(reading); Serial.print(" | Alarm: "); Serial.println(alarm ? "ON" : "OFF"); delay(500); }

How the Functions Work Together

  1. readSensor() obtains a sensor reading.
  2. isThresholdExceeded() checks the reading and returns a Boolean value.
  3. updateLED() uses that Boolean value to control the LED.
  4. loop() coordinates these tasks.

This approach makes each function easier to understand and change.

For example, you could replace the LED with a buzzer or a display while keeping the sensor-reading and threshold-checking functions unchanged.

The threshold is an example value and should be adjusted for the sensor and application.

10. Avoiding Duplicate Code

Suppose two sensors need the same threshold-checking logic.

Instead of writing separate conditions for every sensor, use one reusable function.

bool isHigh(int value, int threshold) { return value > threshold; } void setup() { Serial.begin(115200); int temperatureReading = 35; int lightReading = 2500; Serial.println( isHigh(temperatureReading, 30) ? "Temperature is high" : "Temperature is normal" ); Serial.println( isHigh(lightReading, 2000) ? "Light reading is high" : "Light reading is normal" ); } void loop() { }

The isHigh() function accepts both the reading and the threshold. It can therefore be reused for different types of measurements.

Notice that the meaning of a high reading depends on the sensor. A real project may need separate thresholds and interpretation for different sensors.

11. Pass by Value and Pass by Reference

C++ supports different ways to pass arguments to functions.

Pass by Value

The function receives a copy of the argument.

void changeValue(int number) { number = 100; } void setup() { Serial.begin(115200); int value = 10; changeValue(value); Serial.println(value); } void loop() { }

Output:

10

Changing number does not change the original variable value.

Pass by Reference

A reference parameter allows a function to modify the original variable.

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.

Use references when a function needs to update an existing variable. For simple values that do not need to be modified, passing by value is usually straightforward.

12. Using const for Safer Functions

The const keyword can prevent accidental modification of data through a function parameter.

void printSensorValue(const int value) { Serial.print("Sensor value: "); Serial.println(value); } void setup() { Serial.begin(115200); const int sensorValue = 1800; printSensorValue(sensorValue); } void loop() { }

The function can read value but cannot assign a different value to that parameter.

For larger objects, a const reference can avoid copying the object while preventing modifications through that reference.

void printMessage(const String &message) { Serial.println(message); }

For small built-in types such as int, passing by value is generally appropriate. On memory-constrained embedded devices, avoid unnecessary dynamic allocation and large temporary objects where practical.

13. Function Overloading

Function overloading allows multiple functions to share the same name when their parameter lists differ.

Example

int add(int a, int b) { return a + b; } float add(float a, float b) { return a + b; } void setup() { Serial.begin(115200); Serial.println(add(10, 20)); Serial.println(add(2.5f, 3.5f)); } void loop() { }

The compiler selects the appropriate function based on the argument types.

Function overloading can make related operations easier to use, but the parameter lists must differ. Changing only the return type is not sufficient to overload a function.

14. Organizing ESP32 Code into Multiple Files

As an ESP32 project grows, keeping all the code in one .ino file becomes inconvenient.

You can divide the application into separate files, for example:

SensorProject/ ├── SensorProject.ino ├── SensorUtils.h └── SensorUtils.cpp

Each file has a different responsibility:

  • SensorProject.ino contains the Arduino setup() and loop() functions.
  • SensorUtils.h declares reusable functions.
  • SensorUtils.cpp implements those functions.

This structure makes the code easier to reuse in other projects.

Step 1: Create SensorUtils.h

#ifndef SENSOR_UTILS_H #define SENSOR_UTILS_H int readAnalogSensor(int pin); bool isAboveThreshold(int value, int threshold); #endif

This header declares the functions so other source files can use them.

The #ifndef, #define, and #endif directives form an include guard. They help prevent the header from being processed multiple times in the same compilation unit.

Step 2: Create SensorUtils.cpp

#include <Arduino.h> #include "SensorUtils.h" int readAnalogSensor(int pin) { return analogRead(pin); } bool isAboveThreshold(int value, int threshold) { return value > threshold; }

This file contains the implementations.

Arduino.h provides the Arduino functions and definitions used here, including analogRead().

Step 3: Create SensorProject.ino

#include "SensorUtils.h" const int SENSOR_PIN = 34; const int THRESHOLD = 2000; void setup() { Serial.begin(115200); } void loop() { int reading = readAnalogSensor(SENSOR_PIN); if (isAboveThreshold(reading, THRESHOLD)) { Serial.println("Threshold exceeded!"); } else { Serial.println("Reading is normal."); } delay(1000); }

Important Notes

  • Keep all three files in the same Arduino sketch folder.
  • Use the correct file extensions: .ino, .h, and .cpp.
  • The SensorUtils.h file declares the functions; SensorUtils.cpp defines them.
  • Confirm that GPIO 34 is available and suitable on your particular ESP32 board.
  • If you use ESP-IDF rather than the Arduino framework, project organization and build configuration are different.

15. Reusing Functions Across Multiple Projects

A function becomes more reusable when it does not depend unnecessarily on one specific pin, threshold, or global variable.

For example, this function is tied to one pin:

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

A more reusable version accepts the pin as a parameter:

int readSensor(int pin) { return analogRead(pin); }

You can then use the same function with different suitable pins:

int firstReading = readSensor(34); int secondReading = readSensor(35);

The actual pins must be supported ADC inputs on your ESP32 board.

The same principle applies to LED control, calculations, validation, and data formatting. Pass the information a function needs through parameters rather than embedding unnecessary project-specific values inside the function.

16. Designing Reusable Functions Properly

Good reusable functions should have a clear purpose and predictable behavior.

Use Meaningful Names

Prefer:

int readTemperature();

Instead of:

int func1();

The name should explain the function's task.

Keep Functions Focused

A function that reads a sensor should not also manage Wi-Fi, write a database record, and control several unrelated devices.

Separate responsibilities into functions such as:

int readTemperature(); bool isTemperatureHigh(int temperature); void controlAlarm(bool active);

Avoid Unnecessary Global Variables

Passing values through parameters makes dependencies more visible.

bool isTemperatureHigh(int temperature, int threshold) { return temperature > threshold; }

This function does not need to read or modify a global threshold.

Avoid Repeating the Same Logic

If several parts of your program perform the same operation, consider creating a shared function.

However, do not create a function for every single statement. A function is most helpful when it gives a meaningful name to a task, avoids duplication, or separates a responsibility.

Make Return Values Clear

If a function is designed to check a condition, a Boolean return value is often appropriate.

bool isValidReading(int value) { return value >= 0 && value <= 4095; }

The example range is suitable only for a corresponding configured reading scale. Adapt validation to your sensor and hardware.

17. Practical Project: ESP32 Sensor Alert

This project combines reusable functions, parameters, return values, and conditions.

Objective

Read an analog sensor and activate an LED when its reading exceeds a threshold.

Components

  • ESP32 development board.
  • Analog-output sensor suitable for the selected input voltage.
  • LED and appropriate current-limiting resistor, or an onboard LED if supported.
  • Breadboard and jumper wires.

Example Code

const int SENSOR_PIN = 34; const int LED_PIN = 2; const int ALERT_THRESHOLD = 2000; int readSensor(int pin) { return analogRead(pin); } bool shouldActivateAlert(int value, int threshold) { return value > threshold; } void setAlertLED(int pin, bool active) { digitalWrite(pin, active ? HIGH : LOW); } void printStatus(int value, bool active) { Serial.print("Sensor reading: "); Serial.print(value); Serial.print(" | Alert: "); Serial.println(active ? "ACTIVE" : "INACTIVE"); } void setup() { Serial.begin(115200); pinMode(LED_PIN, OUTPUT); pinMode(SENSOR_PIN, INPUT); } void loop() { int value = readSensor(SENSOR_PIN); bool alertActive = shouldActivateAlert(value, ALERT_THRESHOLD); setAlertLED(LED_PIN, alertActive); printStatus(value, alertActive); delay(500); }

Function Responsibilities

FunctionResponsibility
readSensor()Reads the analog input
shouldActivateAlert()Evaluates the threshold condition
setAlertLED()Controls the LED
printStatus()Displays the current state

How to Test

  1. Connect the sensor output to a supported ADC pin.
  2. Connect the LED through a suitable resistor, or use a supported onboard LED.
  3. Upload the sketch.
  4. Open the Serial Monitor at 115200 baud.
  5. Observe the sensor values.
  6. Adjust ALERT_THRESHOLD based on your readings.
  7. Verify that the LED changes state when the threshold is crossed.

Hardware safety: ESP32 GPIOs use 3.3 V logic and generally are not 5 V tolerant. Ensure the sensor output stays within the permitted input range. GPIO assignments and ADC behavior differ across ESP32 models.

18. Common Mistakes

Mistake 1: Forgetting to Call a Function

Defining a function does not execute it. You must call it from setup(), loop(), or another function.

Mistake 2: Using the Wrong Return Type

A function declared as int should return an appropriate integer value. Use void when the function is not intended to return a value.

Mistake 3: Mismatching Function Parameters

The arguments supplied during a function call must be compatible with the declared parameter types.

For example:

bool isAboveThreshold(int value, int threshold);

A call should supply both arguments:

isAboveThreshold(2500, 2000);

Mistake 4: Repeating the Same Logic

Copying the same code into multiple locations makes updates harder. Consider extracting repeated operations into a function.

Mistake 5: Creating Functions with Too Many Responsibilities

If one function performs many unrelated tasks, divide it into smaller functions with clear purposes.

Mistake 6: Using Unsupported Pins

A reusable function does not make every GPIO suitable for every operation. Verify pin capabilities before using the function with a particular pin.

Mistake 7: Blocking the Main Loop

Long delays and waiting loops can stop the application from handling other work promptly. Use millis()-based scheduling or another appropriate design for responsive applications.

19. Practice Exercises

Beginner

  1. Create a showWelcome() function that prints a welcome message.
  2. Create a function named turnOnLED() that activates an LED.
  3. Write a function that accepts two integers and returns their sum.
  4. Create a function that prints a sensor reading passed as a parameter.

Intermediate

  1. Write a reusable function that determines whether a reading exceeds a threshold.
  2. Create a function that converts an analog reading into an approximate percentage.
  3. Write one LED-control function that works with different GPIOs.
  4. Create separate functions for reading a sensor, evaluating a threshold, and displaying a status.

Advanced

  1. Split a sensor project into .ino, .h, and .cpp files.
  2. Use function overloading to calculate the sum of integer and floating-point values.
  3. Design reusable functions for a smart-lighting system with multiple sensors.
  4. Modify the sensor-alert project to use non-blocking timing with millis().

Summary

Functions make ESP32 programs more organized, readable, and reusable.

In this lesson, you learned about:

  • Function declarations, definitions, and calls.
  • Parameters and return values.
  • Passing arguments by value and by reference.
  • Using const for safer function interfaces.
  • Function overloading.
  • Separating sensor reading, decision-making, and output control.
  • Organizing reusable code into .h and .cpp files.
  • Applying code reusability to an ESP32 sensor-alert project.
  • Writing focused functions with clear responsibilities.

The main principle is simple: write a task once, give it a meaningful name, and reuse it wherever appropriate. This approach helps you build larger ESP32 and IoT applications without unnecessary duplication.

Keep learning. Keep building. Keep growing.

© 2026 Ugenz Academy