Labs / Arduino + ESP32 with Wokwi

23 Modularization Programming: Library File Encapsulation

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

Contents

1. Introduction

In the previous chapters, we have learned to use function encapsulation to reduce redundant code. However, all the functions so far are written in the same. ino file:

To address these issues, we need to implement the functional modules as independent library files. The advantages of this approach are as follows:

This chapter will delve into how to encapsulate the functions of the ultrasonic ranging module into an independent library file. Through this process, we will not only learn how to write library files, but also master how to flexibly use them in projects, making our code more Modularization, easier to maintain, and providing scalable solutions for more complex engineering projects.

2. Library Files

2.1 What is a Library File

A library file (Library) is a set of pre-written code that encapsulates the Code Blocks we commonly use for implementing specific functions into a single file, making it convenient to reuse across multiple projects.

It usually consists of two parts:

. c source file: implements the specific logic of the function.

. h Header File: declares functions, constants, variables, etc. , and defines interfaces.

2.2 Writing Library Files

2.2.1 Supplementary Basics

We need to first supplement some necessary basic knowledge

Preprocessor Directive:

Instructions starting with # are what we refer to as "preprocessing directives".

In the previous code, the #include used to reference library files and the #define used when defining constants are both preprocessing directives.

The compiler does not directly compile the preprocessing directives; instead, it preprocesses these directives completely before the compilation process begins.

Macro definition:

#define 宏名 值

#define trigPin 23   // Trigger pin
#define echoPin 22   // Echo pin

If we use #define to define two constants in a program, then before the actual compile, the system will replace all macro names in the code with their corresponding values, and then compile the replaced code.

Header File Reference:

In our code, if you use #include to include a Header File, for example:#include "SR04.h"

Then during preprocessing, the system will replace this statement with the actual content in the SR04.h file, and then compile the replaced code.

// Used to include header files provided by the system or standard libraries. The compiler searches for the file in the default system library paths, so you do not need to provide the path yourself.
#include <文件名>
// Used to include header files you wrote yourself or other files in the project. The compiler first searches for the file in the current working directory. If not found, it then searches the standard library paths.
#include "文件名"

Header File Guard:

When a Header File is referenced by multiple source files, it may be included by the compiler multiple times.

In the Header File, we often see the following code, which is a method of Header File guard designed to prevent the compiler from repeatedly compiling the same Header File.

#ifndef SR04_H
#define SR04_H

.
.
.

#endif
2.2.2 Header File (. h)

The declaration section of the library file mainly includes the following contents:

#ifndef SR04_H
#define SR04_H

// Define pins, the digital pin numbers of the trigger pin and echo pin
#define trig_Pin 23   // Trigger pin
#define echo_Pin 22   // Echo pin

// Function declarations
void SR04_begin(int trigPin, int echoPin);  // Initialize pins
float measureDistance(int trigPin, int echoPin);  // Measure distance

#endif
2.2.3 Source Files (. c or. cpp)

The implementation part of the library file mainly contains the specific implementation of the function.

These implementations are the parts that the program actually executes, that is, how you implement the functions declared in the Header File.

The code in the source file typically includes:

#include <Arduino.h>
#include "SR04.h"

// 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
  
  // Print the distance to the serial port
  Serial.print("Distance: ");
  Serial.print(distance);  // Print the distance value
  Serial.println(" cm");   // Unit is centimeters

  return distance;  // Return the measured distance
}

2.3 Calling Library Files

2.3.1 Importing Library Files

In the. ino file, import the Header File via #include so that the program can recognize the functions and variables declared in the library file.

2.3.2 Calling functions in the library

Call the encapsulated functions or methods in the library in the main program. For example, in this case, we call SR04_begin () to initialize the pins, and call measureDistance () to obtain the ranging data.

2.3.3 Implementation Code

Use library functions: such as SR04_begin () and measureDistance (), without needing to concern yourself with the specific implementation.

#include "SR04.h"  // Include the custom SR04 library file, which contains the ultrasonic module functions

void setup() {
  Serial.begin(9600);    // Initialize serial communication to output the measurement results
  SR04_begin(trig_Pin, echo_Pin);  // Initialize the pins of the ultrasonic module
}

void loop() {
  // Call the measureDistance function to measure the distance; the returned distance is in centimeters
  float distance = measureDistance(trig_Pin, echo_Pin);  

  delay(1000);  // Measure once per second
}

3. Complete Example

4. Summary of This Chapter

In this chapter, we further learned about the advanced method of Modularization programming — library file encapsulation.

In previous studies, we have avoided redundant code through function encapsulation. However, as the number of functions gradually increases, if all the code is piled up in the. ino file, the main program will appear lengthy and chaotic, which is not conducive to management and reuse.

To address these issues, we introduce the concept of Library, which typically consists of Header File (. h) and Source File (. c/. cpp):

Through the practical case (ultrasonic module SR04) in this chapter, we have accomplished the following contents:

  1. Extract the ranging function from the main program and encapsulate it independently into the library file;
  2. In the main program, simply #include "SR04.h" to call SR04_begin () and measureDistance ();
  3. The main program remains concise, focusing solely on logical control, while the underlying implementation is uniformly managed by library files;
  4. When other projects need to use the ultrasonic module, this library file can be directly reused without repeated coding.

It can be said that library files are an essential path for moving from simple experiments to complex engineering development. They make our code more professional and engineering-oriented, and also lay a solid foundation for subsequent learning of Object Oriented programming (library file encapsulation of classes and objects).