Labs / Arduino + ESP32 with Wokwi

22 Modularization Programming: function Encapsulation

Author: Li Zisheng · Source: FreakStudio open documentation · License: CC BY 4.0

Contents

In embedded development, as project scales expand and complexity increases, we commonly face a recurring set of pain points: code duplication, cumbersome modification, and convoluted maintenance. These issues become particularly pronounced when working with multiple sensor modules, such as deploying several ultrasonic modules for multi-directional distance measurement. Whenever we run into these problems, figuring out how to write cleaner, more maintainable code becomes a top priority we have to address.

This chapter will demonstrate to you how to solve these problems through Modularization programming by applying the ultrasonic ranging module. We start with the most basic function encapsulation, encapsulating repeated operations into reusable functions, which avoids code redundancy and improves the readability and maintainability of the code at the same time. Through encapsulation, we can not only make the code clearer and easier to understand, but also easily expand more functions in the project, such as adding support for multiple ultrasonic modules, without worrying about the increase in code complexity.

In this chapter, you will learn how to use function encapsulation to optimize the control of the ultrasonic module, reduce redundant code, and maintain a concise and efficient code structure.

1. Introduction

We have already learned how to use the ultrasonic module earlier, and the implementation process of the code is quite simple: send out an ultrasonic pulse through the trigger pin, then measure the time of the reflected echo via the echo pin, and finally calculate the distance and display it on the serial monitor.

This code works perfectly fine in beginner-level projects, but as our project gradually grows more complex, problems will start to emerge.

1.1 Problems in Complex Projects

Suppose we want to work on a more complex project that requires multiple ultrasonic modules (for example, three ultrasonic modules) to measure distances in different directions respectively. Here comes the problem:

Like this:

// ================================
// Example: three ultrasonic modules written independently (inefficient, not recommended)
// ================================

#define TRIG_PIN1  5
#define ECHO_PIN1  18

#define TRIG_PIN2  17
#define ECHO_PIN2  16

#define TRIG_PIN3  4
#define ECHO_PIN3  2

void setup() {
  Serial.begin(115200);

  pinMode(TRIG_PIN1, OUTPUT);
  pinMode(ECHO_PIN1, INPUT);

  pinMode(TRIG_PIN2, OUTPUT);
  pinMode(ECHO_PIN2, INPUT);

  pinMode(TRIG_PIN3, OUTPUT);
  pinMode(ECHO_PIN3, INPUT);
}

void loop() {
  // Module 1
  digitalWrite(TRIG_PIN1, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG_PIN1, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN1, LOW);
  long duration1 = pulseIn(ECHO_PIN1, HIGH);
  float distance1 = duration1 * 0.034 / 2;
  Serial.print("Module1 Distance: ");
  Serial.println(distance1);

  // Module 2
  digitalWrite(TRIG_PIN2, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG_PIN2, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN2, LOW);
  long duration2 = pulseIn(ECHO_PIN2, HIGH);
  float distance2 = duration2 * 0.034 / 2;
  Serial.print("Module2 Distance: ");
  Serial.println(distance2);

  // Module 3
  digitalWrite(TRIG_PIN3, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG_PIN3, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN3, LOW);
  long duration3 = pulseIn(ECHO_PIN3, HIGH);
  float distance3 = duration3 * 0.034 / 2;
  Serial.print("Module3 Distance: ");
  Serial.println(distance3);

  delay(500);  // Update every 0.5 s
}

1.2 Solutions for Modularization Programming

At this point, modularization programming becomes particularly important. Modularization programming helps us break down code into independent, clearly functional small modules, so that:

Through Modularization, programs become more flexible, efficient, and easy to debug. When errors occur in the code, it is also more convenient to locate the problem.

1.3 How to Implement Modularization Programming?

So, what on earth is modularization programming?

Actually, Modularization programming is to divide the code into multiple small modules with clear functions, and we can use functions or classes to encapsulate these modules.

In the following course, we will start with the most basic function encapsulation first, and then gradually introduce how to organize code into modules with independent functions, ultimately helping you write more efficient and maintainable code.

2. Function Encapsulation: The First Step of Basic Modularization

At this point, Modularization programming becomes particularly important. It helps us break down the functions in a program into independent small modules, which not only avoids redundant code but also improves code readability.

We only need to focus on the function of each module, without having to search through and modify the code scattered across the entire codebase.

So, how exactly should Modularization programming be implemented? Next, we will start with the most basic function encapsulation.

2.1 Function Review

In programming, a function is an independent Code Block that performs a specific task.

When we encounter operations that need to be performed repeatedly, we can encapsulate them into a function. A function implements Modularization via input (parameters) and output (return values), so that the same set of operations can be reused multiple times.

Take the example of distance measurement using an ultrasonic module:

  • We need to measure the distance multiple times, which will result in a lengthy segment of code dedicated to acquiring ultrasonic data and calculating the distance in the program.
  • If these operations repeatedly occur in multiple places, the code will appear redundant and difficult to maintain.

At this point, we can encapsulate the ranging capability into a function. This way, no matter where we need to use it, we only have to call this function.

2.2 Usage Encapsulation with function

Next, we will take the code of the ultrasonic module from the last class as an example to carry out encapsulation.

We will encapsulate the pin configuration function of the ultrasonic module into SR04_begin. This function only completes the initialization of the ultrasonic module and does not require a return value, so we use void as the return type.

// Function: pin initialization
void SR04_begin(int trigPin, int echoPin) {
  pinMode(trigPin, OUTPUT);  // Set trigger pin as output
  pinMode(echoPin, INPUT);   // Set echo pin as input
}

Encapsulate the process of sending a trigger signal, acquiring data and calculating the result into the measureDistance function. This function should finally return the measured distance, which is a variable of type float. Therefore, we name this function with the float type, and add a return statement in the function to return the variable value and exit the function.

// Function: distance measurement
float measureDistance(int trigPin, int echoPin) {
  // Send ultrasonic pulse
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  // Receive echo and calculate distance
  long duration = pulseIn(echoPin, HIGH);
  float distance = duration * 0.0344 / 2; // Calculate distance

  return distance;  // Return the measured distance
}

2.3 Declare and Call a Function

After the encapsulation is completed, we can just call it in the main function.

If a custom function is placed before the main function, no additional declaration is required;

If it is located after the main function, a function declaration needs to be made before the main function to call it.

#define trig_Pin 23   // Trigger pin
#define echo_Pin 22   // Echo pin

// Function: pin initialization
void SR04_begin(int trigPin, int echoPin) {
  pinMode(trigPin, OUTPUT);  // Set trigger pin as output
  pinMode(echoPin, INPUT);   // Set echo pin as input
}

// Function: distance measurement
float measureDistance(int trigPin, int echoPin) {
  // Send ultrasonic pulse
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  // Receive echo and calculate distance
  long duration = pulseIn(echoPin, HIGH);
  float distance = duration * 0.0344 / 2; // Calculate distance

  return distance;  // Return the measured distance
}

void setup() {
  Serial.begin(9600);  // Initialize serial communication
  SR04_begin(trig_Pin, echo_Pin);  // Initialize pins
}

void loop() {
  // Call the distance measurement function to get the distance
  float distance = measureDistance(trig_Pin, echo_Pin);

  // Output the measurement result
  Serial.print("Distance: ");
  Serial.print(distance);
  Serial.println(" cm");

  delay(1000);  // delay 1 second
}

Now the code in the main function is very clear and straightforward.

2.4 Taking three ultrasonic modules as an example

When we have multiple ultrasonic modules, we only need to assign trig pins and echo pins to different modules, then initialize them separately in setup (), and call loop () to call measureDistance (). This avoids redundant code and greatly improves the maintainability of the program.

// ================================
// 2.4 Example with three ultrasonic modules
// ================================

// Module 1
#define TRIG1 23
#define ECHO1 22

// Module 2
#define TRIG2 19
#define ECHO2 18

// Module 3
#define TRIG3 5
#define ECHO3 4

// Function: pin initialization
void SR04_begin(int trigPin, int echoPin) {
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

// Function: distance measurement
float measureDistance(int trigPin, int echoPin) {
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  long duration = pulseIn(echoPin, HIGH);
  float distance = duration * 0.0344 / 2;

  return distance;
}

void setup() {
  Serial.begin(9600);

  // Initialize the three modules
  SR04_begin(TRIG1, ECHO1);
  SR04_begin(TRIG2, ECHO2);
  SR04_begin(TRIG3, ECHO3);
}

void loop() {
  // Module 1 distance measurement
  float d1 = measureDistance(TRIG1, ECHO1);
  Serial.print("Module1 Distance: ");
  Serial.print(d1);
  Serial.println(" cm");

  // Module 2 distance measurement
  float d2 = measureDistance(TRIG2, ECHO2);
  Serial.print("Module2 Distance: ");
  Serial.print(d2);
  Serial.println(" cm");

  // Module 3 distance measurement
  float d3 = measureDistance(TRIG3, ECHO3);
  Serial.print("Module3 Distance: ");
  Serial.print(d3);
  Serial.println(" cm");

  Serial.println("--------------------------");

  delay(1000); // Update every 1 s
}

3. Complete Example

4. Summary of This Chapter

In this chapter, we take the ultrasonic ranging module as an example to systematically introduce the idea and practice of function encapsulation and Modularization programming.

First, through the "repetitive coding pattern" of the three ultrasonic modules, we identified issues including code redundancy, difficult modification, and complicated maintenance — these are exactly the typical challenges that beginners encounter as their projects grow more complex.

Then, we introduced the solution of Modularization programming ——using function encapsulation to extract the repeated functions:

Based on a single module, we further extend to the application of multiple ultrasonic modules. By configuring independent pins for different modules and then calling the same ranging function, we can easily realize multi-directional ranging. Compared with the original "copy-paste" coding method, this approach is more concise and has stronger scalability.

After studying this chapter, you should be able to:

  1. Understand Modularization programming the advantages and necessity of modular programming;
  2. Master how to encapsulate via function to avoid code duplication;
  3. Learn to use multiple sensor modules simultaneously in a project while maintaining a clean code structure.