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:
- As functions increase in number, the main program will become verbose and hard to read;
- If there are multiple sensor modules in a project, the code tends to be messy and difficult to maintain;
- If you also need to use these functions in other projects, you have to copy and paste or rewrite them, which is not only cumbersome but also error-prone.
To address these issues, we need to implement the functional modules as independent library files. The advantages of this approach are as follows:
- Clear structure: the main program only retains logical control, while specific functions are managed by library files;
- Easy to reuse: once the library file is written, any project only needs to
#includeit to call the functions directly; - Easy to maintain when the library file is modified, all projects that use it can be updated synchronously;
- Modularization Programming: Each sensor/function module has an independent file without interfering with each other.
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 pinIf 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#ifndef SR04_H#ifndefis an abbreviation of "if not defined", meaning "ifSR04_Hhas not been defined".- It is used to check whether the macro
SR04_H(which serves as the file protection identifier here) has been defined. IfSR04_His not defined, the subsequent code will be executed; if it has already been defined, the compiler will skip the following part.
#define SR04_H- This line defines the
SR04_Hmacro. When the#ifndefcondition is satisfied, that is, whenSR04_His not defined,#define SR04_Hwill define it. - In this way, when encountered again during the next compile,
#ifndef SR04_H,SR04_Hwill have already been defined, so the code will not enter this section again.
- This line defines the
#endif-
#ifndefEnd flag for conditional compile, which tells the compiler that the conditional compile block ends here. - In this way, the Header File can be safely included multiple times without causing problems such as duplicate definitions and compile errors.
-
2.2.2 Header File (. h)
The declaration section of the library file mainly includes the following contents:
- Include Guard: To prevent the Header File from being included repeatedly, we use
#ifndef,#defineand#endifin the Header File to ensure that the same Header File will not be included multiple times in the same program. - Macro definitions, constants, type definitions, etc. : You can declare constants, structures, classes, macros and other content in a Header File, and these contents can be shared by multiple source files.
- function declaration: It defines the name, parameters and return value type of the function in the library, but does not include a concrete implementation. This allows other programs to call the functions in the library by referencing this Header File without needing to know the specific implementation details of the functions.
#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
#endif2.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:
- function implementation: the concrete implementation of the function declared in the Header File.
- Other related functions: There may be some auxiliary functions used to implement specific functions.
- Include Header File: In the source file, you need to include the Header File you wrote yourself (for example,
#include "SR04.h") so that the compiler knows how to match function declarations and definitions.
#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
Ultrasonic Library - Wokwi ESP32, STM32, Arduino Simulator
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):
- Header File: used to declare function, macro definitions, constants, etc. , and prevent duplicate inclusion via Header File Guard;
- Source File: implements the specific logic of the function, and corresponds to the Header File via
#include "xxx.h".
Through the practical case (ultrasonic module SR04) in this chapter, we have accomplished the following contents:
- Extract the ranging function from the main program and encapsulate it independently into the library file;
- In the main program, simply
#include "SR04.h"to callSR04_begin ()andmeasureDistance (); - The main program remains concise, focusing solely on logical control, while the underlying implementation is uniformly managed by library files;
- 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).