1. Introduction
Fuzzy logic controllers (FLCs) have become essential elements in modern control systems across a variety of industries, particularly in automotive applications. Unlike traditional crisp controllers, which depend on precise mathematical models and binary logic, FLCs effectively manage imprecision and uncertainty by simulating human reasoning. This adaptability makes them especially suitable for complex systems where deriving or implementing exact models is challenging.
The proposed fuzzy logic control system for an advanced driver-assistance system (ADAS) builds upon this adaptability, offering a range of key features designed to enhance vehicle safety and driver comfort. By integrating a low-cost ultrasonic sensor (HC-SR04) and an STM32 microcontroller, the system provides real-time adjustments to braking force based on inputs such as proximity sensing, vehicle speed, and road conditions. The fuzzy logic controller processes these three inputs, employing a unique set of fuzzy rules to generate a smooth and adaptive brake response. This approach overcomes the limitations of traditional binary systems that might cause abrupt and unsafe braking actions.
One of the principal benefits of this system is its reduced reliance on precise mathematical modeling. Traditional crisp controllers often require an extensive understanding of system dynamics, making it challenging to design them for complex or nonlinear systems. In contrast, the FLC operates using linguistic variables and fuzzy sets, which allows control strategies to be formulated based on expert knowledge and heuristic rules rather than exact equations.
Furthermore, the system demonstrates robustness in handling noise and disturbances in sensor data, a common issue in real-world automotive environments, where sensors are subjected to various forms of interference. The fuzzy logic’s ability to tolerate ambiguity ensures the system remains functional, maintaining safety and reliability even under uncertain conditions.
Current applications of FLCs in the automotive industry include anti-lock braking systems, traction control, and advanced driver-assistance systems like adaptive cruise control and lane-keeping assistance. The proposed system advances these applications by offering a cost-effective model that paves the way for more sophisticated systems in future vehicular technologies. Ultimately, this fuzzy logic-based approach provides a promising framework for addressing the complexities of modern automotive control systems.
2. Literature Survey and State of the Art
Fuzzy logic has been extensively researched and applied across various industries, notably automotive systems, where uncertainty and imprecision are common in real-world data. Key studies have demonstrated the effectiveness of fuzzy logic in systems such as anti-lock braking [
1], adaptive cruise control [
2], and traction control [
3]. For example, Elsayed Hossam’s work [
4] on fuzzy logic in collision avoidance systems provides a strong example of a modern fuzzy application. Subsequent advancements have focused on embedding fuzzy logic into systems to enhance performance and safety. I. Riziani’s research [
5] highlights the benefits of using fuzzy logic in car braking systems with the Mamdani model, similar to the approach in this paper. An intelligent fuzzy logic algorithm has been developed to apply brakes automatically, regardless of speed or distance to an object, to prevent or mitigate collisions [
6]. T. Peng’s research [
7] uses an ultrasonic ranging solution similar to the presented approach but using Sugeno fuzzy inference.
State-of-the-art proximity detection systems in advanced driver-assistance systems (ADAS) rely on high-resolution sensors like LiDAR [
8], radar, and ultrasonic sensors, combined with complex algorithms. Many commercial systems employ machine learning or deep learning to improve decision-making but often require substantial computational resources and extensive training data. While machine learning offers predictive accuracy, its reliance on data and computational power makes it less suitable for resource-constrained environments, such as entry-level or cost-sensitive vehicles. For instance, A. Moujahid’s work examines the best-suited ML techniques for ADAS applications [
9]. The authors in [
10] propose a novel clustering algorithm, multivariate fuzzy density-based temporal–spatial clustering of applications with noise, designed to create well-defined clusters by integrating multivariate, fuzzy, temporal, and spatial features to tackle challenges such as the proximity, crossing, and overlapping of targets across range, Doppler, and angle. Similarly, [
11] investigates a multiple-input multiple-output fuzzy adaptive data-driven security control strategy for high-speed trains, addressing challenges from actuator faults and dynamic sensor attacks.
This paper bridges the gap between traditional crisp control systems and costly state-of-the-art solutions. By implementing a fuzzy logic controller on an STM32 microcontroller [
12], it demonstrates that robust and flexible proximity detection can be achieved with affordable hardware and simple algorithms. Unlike market solutions, requiring large-scale computational infrastructure or extensive sensor arrays, this approach employs an ultrasonic sensor [
13] for distance measurement, which is cost-effective and suited for academic use. Although not as precise as LiDAR or radar-based systems, the fuzzy logic-based method provides significant adaptability and noise tolerance, making it a viable alternative for automotive applications in academic settings.
Table 1 summarizes the key points from the literature survey and state-of-the-art discussion. This table presents the main contributions and focus areas of various studies.
3. Concept
This paper aims to design and implement a fuzzy logic controller for a vehicle proximity detection system, modeled after the functionality present in modern automotive models. The primary goal is to develop a system capable of detecting obstacles at various distances—categorized as Far, Medium, and Near—and determining the appropriate braking force based on fuzzy logic principles.
An ultrasonic distance sensor will be employed to measure obstacle proximity in real time. This sensor data will be processed by an STM32 microcontroller, which acts as the system’s core processor. The microcontroller will execute fuzzy logic algorithms that include fuzzification of input variables, rule evaluation, and defuzzification to generate a crisp output for determining the braking force.
The system will use overlapping fuzzy zones for distance measurements to replicate the gradual perception of proximity, similar to human judgment. Additionally, speed and road conditions will be considered as input variables, enhancing the system’s capacity to make nuanced decisions. Road conditions will be represented by a Road Condition Index (RCI), taking into account factors like wet or icy surfaces that could impact braking efficiency.
Communication between the microcontroller and other simulated vehicle systems will be managed using the Controller Area Network (CAN) protocol [
14]. This ensures that the proximity detection system can interact seamlessly with other Electronic Control Units (ECUs), simulating a real automotive environment.
Figure 1 illustrates the overall concept and the components of the proposed system.
4. Requirements
In this section, we outline the complete system requirements. The paper is divided into two sections: the Fuzzy Logic Controller (FLC) and the CAN monitor test tool.
4.1. System Requirements
Table 2,
Table 3 and
Table 4 present the requirements for the proposed system in the following categories: the hardware requirements for the fuzzy logic controller, the software requirements for the FLC, and the software requirements for the CAN monitor application, respectively.
Figure 2 presents the Data Flow Diagram (DFD) of the proposed system. It illustrating how inputs are stimulated and processed, providing a comprehensive overview of the system’s global functionality. The DFD shows the design flow of the proposed system.
Similarly,
Figure 3 depicts the Data Flow Diagram for the CAN monitor and test case tool, which manages the reception and processing of CAN messages sent from the Fuzzy Logic Controller (FLC).
4.2. Ultrasonic Sensor Handling Requirements
This section describes the requirements for handling the HC-SR04 sensor.
Table 5 shows the ultrasonic sensor handling requirements.
4.3. CAN Configuration Requirements
This section describes the speed configuration needed for the Controller Area Network.
Table 6 shows the CAN configuration requirements.
4.4. Non-Functional Requirements
Due to the nature of the project described in this paper, several non-functional requirements must be considered. These include the necessary number of LEDs to represent the distance to an obstacle and the minimum number of test cases required for system validation.
Additionally, a third non-functional requirement involves specifying the maximum and minimum distances needed for effective object detection.
5. Proposed Design Elements
This section describes the elements used for the project in this paper for both hardware and software.
5.1. Hardware—Fuzzy Logic Controler
The project described in this paper utilizes the NUCLEO 431KB development board as its central processing unit.
Figure 4 illustrates the port and pin usage. This STM32 microcontroller board features an Arm Cortex-M4 core, offering sufficient computational power and integrated features necessary for implementing the fuzzy logic controller. Its compact form factor and compatibility with various peripherals make it ideal for processing sensor data, executing fuzzy algorithms, and handling communication protocols essential for the proximity detection system.
To enable communication with other simulated vehicle systems, the project incorporates a CAN FD transceiver (NXP TJA1441AT, DigiKey, 701 Brooks Avenue South, Thief River Falls, MN, USA) [
15]. This transceiver facilitates reliable, high-speed data transmission via the Controller Area Network Flexible Data-Rate (CAN FD) protocol. The NXP TJA1441AT ensures robust communication by interfacing the microcontroller’s CAN controller with the physical CAN bus. This setup allows the proximity detection system to send and receive messages within an automotive network environment. To achieve a speed of 500 Kbps, the CAN module was configured as depicted in
Figure 5.
For obstacle detection, the paper employs the HC-SR04 ultrasonic sensor (DigiKey, 701 Brooks Avenue South, Thief River Falls, MN, USA). This sensor measures the distance to objects by emitting ultrasonic pulses and calculating the time it takes for the echoes to return. The HC-SR04 provides the accurate distance measurements necessary for the fuzzy logic controller to evaluate proximity levels (Far, Medium, Near). Its simplicity and ease of integration with the microcontroller make it an effective choice for real-time distance sensing in the system.
5.2. Software—Fuzzy Logic Controller
Figure 6 illustrates the software architecture of the project described in this paper. The main program integrates key functionalities, including the fuzzification of inputs (speed, distance, and road Conditions), rule evaluation, defuzzification of the brake force, and management of CAN messages. It employs callback functions triggered by interrupts (IRQ_TIM2 and IRQ_UART) to enable real-time processing of ultrasonic sensor data (ECHO) and serial inputs (speed and road Conditions). The HAL libraries for GPIO and CAN facilitate hardware interactions, enabling control of distance LEDs and the transmission of CAN messages.
This modular structure ensures the smooth flow of data between the sensors, the fuzzy logic engine, and the vehicle’s communication system, enhancing the system’s overall efficiency and reliability.
Figure 7 shows a snapshot of a single input call data process of the proposed FLC.
5.3. CAN Monitor and Manual Test Panel Tool
The CAN Monitor and Manual Panel Tool allows users to (i) watch brake-force and status messages (IDs 0x722, 0x723), (ii) run any of the 10 predefined test cases stored in a .csv file, and (iii) override speed and road-condition inputs through the STM32′s USART link.
Developed in NI LabVIEW 2024 Q4 and using NI-XNET to drive an NI USB-8502 CAN adapter, the tool also launches the NI TestStand [
16] engine whenever the Auto-Run option is selected. The left side of
Figure 1 depicts the overall test-bench architecture and its test-executive flow, while
Figure 8 shows the main panel of the CAN tool: incoming CAN frames are listed at the upper left, manual controls for speed and road condition occupy the right, and TestStand-generated results stream in the lower pane.
6. Fuzzy System Design
This section outlines the design approach utilized in the paper, which is divided into three parts:
Linguistic Variable Description and Membership Function Calculations: This part involves defining the linguistic variables and calculating the membership functions necessary for the system.
Fuzzy Rule Creation: This stage focuses on developing the set of fuzzy rules that govern the system’s decision-making process.
Fuzzy Inference Process Using the Mamdani Method and Defuzzification: This section describes the application of the Mamdani method for fuzzy inference and the process of defuzzification to convert fuzzy outputs into crisp values.
Figure 9 illustrates the overall system model implemented in MATLAB version R2024b (24.2.0.2712019) [
17].
6.1. Linguistic Variables and Fuzzification
This section describes the membership functions for each input and output.
Speed: This input uses three linguistic values: low, medium and high. The following equations are used to derive these values, as shown in
Figure 10:
Distance: This input uses three linguistic values: close, medium and far. The following equations are used to derive these values, as shown in
Figure 11:
Road Conditions: This input uses three linguistic values: icy, wet, and good. The following equations are used to derive these values, as shown in
Figure 12.
Brake Force: This output uses three linguistic values: light, moderate, and hard. The following equations are used to derive these values, as shown in
Figure 13.
The brake force is then multiplied by 100 at the end of the process.
The road-condition input is a special case; its membership functions use the variable , representing the Road Condition Index (RCI), ranging from 0 (worst conditions) to 1 (best conditions).
6.2. Fuzzy Rules
The maximum number of rules that the proposed system can use is 27 (3*3*3). The system uses 20 rules. Here are the first 10 rules in the system:
- (1)
If Speed is Low and Distance is Far and Road Conditions are Good then Brake Force is Light.
- (2)
If Speed is Low and Distance is Close and Road Conditions are Icy then Brake Force is Moderate.
- (3)
If Speed is High and Distance is Close and Road Conditions are Icy then Brake Force is Hard.
- (4)
If Speed is High and Distance is Medium and Road Conditions are Wet then Brake Force is Hard.
- (5)
If Speed is Medium and Distance is Close and Road Conditions are Good then Brake Force is Hard.
- (6)
If Speed is Medium and Distance is Far and Road Conditions are Wet then Brake Force is Moderate.
- (7)
If Speed is Low and Distance is Close and Road Conditions are Good then Brake Force is Moderate.
- (8)
If Speed is High and Distance is Far and Road Conditions are Good then Brake Force is Moderate.
- (9)
If Speed is Medium and Distance is Medium and Road Conditions are Icy then Brake Force is Hard.
- (10)
If Speed is Low and Distance is Far and Road Conditions are Wet then Brake Force is Light.
Figure 14 shows the MATLAB viewer where all 20 rules of the system are fired (executed).
6.3. Fuzzy Inference Process
This section discusses the evaluation of fuzzy rules using the Mamdani method. Below is a code snippet demonstrating the implementation of rule number 1 in the system using MATLAB script language:
void evaluateFuzzyRules(SpeedMF speedMF, DistanceMF distanceMF,
RoadConditionMF roadMF, FuzzyRule* rules){
rules[0].firingStrength = fminf(fminf(speedMF.low, distanceMF.far), roadMF.good);
rules[0].brakeForceOutput = LIGHT_BRAKE_FORCE;
In the above code snippet, each rule element is associated with a firing strength and a brake force output. By using the fminf function, the system selects the minimum value among the input membership degrees for each rule condition. This approach helps determine the degree to which a fuzzy rule is activated. Only the rules with non-zero firing strengths contribute to the calculation of the final brake force, ensuring that only relevant inputs influence the system’s output.
6.4. Defuzzification
Defuzzification is the final step for the FLC system. It converts the brake force output generated by the fuzzy inference process into a single crisp value. The defuzzification process calculates the brake force based on the fuzzy rules and their respective firing strengths.
This paper uses the Centroid Method. This method calculates the crisp output by finding the center of gravity of the aggregated fuzzy output, as follows:
where
- -
Firing Strength (αi): activation level of each rule.
- -
Representative value: a predefined crisp value associated with each output fuzzy set.
Figure 15 illustrates the MATLAB surface plot that represents the relationship between the two inputs, speed and distance, and the output, brake force. This surface visualizes how the system’s rules interact to determine the brake force across various combinations of speed and distance inputs, providing a comprehensive view of the fuzzy logic controller’s behavior.
Figure 16 illustrates the MATLAB surface plot that represents the relationship between the two inputs, speed and road condition, and the output, brake force. This surface visualizes how the system’s rules interact to determine the brake force across various combinations of speed and road-condition inputs, providing a comprehensive view of the fuzzy logic controller’s behavior.
7. Development Process
This section outlines the process model implemented for the design in this paper, along with a summary of the release dates for each design phase.
The V-model development process, shown in
Figure 17, was adopted to ensure a structured and systematic approach, emphasizing verification and validation at each stage. The process began with the Requirement Definition phase, where the high-level needs of the system were identified, such as the ability to calculate brake force based on speed, distance, and road conditions. This phase established a foundation for the subsequent stages, ensuring clarity and traceability throughout the development process.
Following the Requirement Definition phase, hardware assembly was carried out, including components like the NUCLEO-G431KB, the HC-SR04 ultrasonic sensor, and the CAN FD transceiver. Basic drivers for CAN and UART communication were developed to facilitate interaction between these components and the STM32 microcontroller. In parallel, the fuzzy logic input membership functions and rule definitions were crafted, alongside core system functions like defuzzification, enabling the system to process sensor data and compute brake force. Mock testing was conducted at each stage to ensure the accuracy and reliability of individual components, such as verifying fuzzy rule behavior and brake force outputs under simulated conditions.
On the validation side of the V-model, rigorous testing was performed for each development phase. Communication functionality was tested through mock tests for CAN and UART, while the fuzzy logic rules and brake force calculations were validated with specific test cases. System-level testing involved the use of a CAN monitor to assess real-world performance, ensuring that the integration of hardware and software met the defined requirements. This iterative process, combined with thorough documentation, ensured that the final implementation aligned with the paper’s objectives. The V-model [
18] not only enhanced the system’s reliability but also provided a clear structure for tracking progress and systematically addressing issues.
Table 7 shows the details of the design management tasks.
8. Results
The metrics used to validate the requirements of this paper include the system’s ability to display PASS/FAIL criteria, data validation, and test case modularity. This section presents the results for these three aspects.
8.1. PASS/FAIL Criteria
There are four functional test cases outlined in a .csv file to assess the functionality of the FLC. These test cases involve setting specific speed and road conditions, with an expected output value to compare against.
Table 8 shows the details of the input values sent via serial transmission to the FLC and the expected resulting brake force.
To verify that the fuzzy controller remained reliable under sensor uncertainty, a noise-robustness sweep was performed. Clean distance and speed profiles
and
were replayed through the hardware in the loop (HIL) test bench while zero-mean Gaussian noise was injected:
with
and
.
For each noise level, 100 Monte-Carlo cycles were logged and the brake-force error was quantified by
where
is the baseline response. A test was set to PASS when
and
for 95% of runs, demonstrating that the fuzzy controller maintained accuracy even with distance noise up to 6 cm rms and speed jitter of 5 km/h.
Figure 18 shows evidence of the system’s behavior based on the inputs described in
Table 8 since TestStand reads the sequences defined in
Table 8 then executes them automatically, and records pass/fail data.
The Fault Insertion column indicates that a random delay [
19] was introduced (ms), increasing the FLC’s response latency and delaying the brake-force response. Therefore, the test executive failed the test case.
8.2. Data Validation
The FLC generates the expected information through CAN messages. As shown in
Figure 19, Message 0x723 contains data from the entire system. Bytes 0–1 encode the distance information, bytes 2–3 represent the speed data, and bytes 4–5 convey the road conditions. The following code snippet exemplifies how the software packages these components before transmission via CAN. This process is similarly applied to the rest of the inputs and outputs.
// Pack the Distance into TxData
TxData[0] = (uint8_t)(Distance & 0xFF);
// LSB
TxData[1] = (uint8_t)((Distance >> 8) & 0xFF); // MSB
/*Sends the status of the system via CAN periodically*/
sendCanMessage(&hfdcan1, &TxHeaderSysStatus, TxData);
Message 0x722 contains the information of the defuzzified brake force which can also be seen in the CAN traffic in
Figure 19.
8.3. Test Case Modularity
The test cases are outlined in a .csv file, as shown in
Table 8. This table format allows users to easily add additional test cases at any time. To update the system with new test cases, users need to click the “Reload Config File” button located at the bottom right of the CAN monitor application, ensuring that the CAN monitor and test case engine incorporate the latest test scenarios.
Table 9 outlines the key differences between a fuzzy logic controller and a non-fuzzy solution.
8.4. Unit Test Cases
The unit test cases were developed using the Unity framework [
20], a lightweight, flexible, and portable unit testing framework specifically designed for C language applications, particularly in embedded systems. Unity enables test-driven development (TDD) and provides detailed feedback on code correctness and behavior. The generated test cases were then executed through NI TestStand, a test management environment that integrates seamlessly with LabVIEW. Unity test scripts were called via command-line interfaces within TestStand, which evaluated test outcomes based on PASS/FAIL criteria.
// fuzzifySpeed tests
RUN_TEST(test_fuzzifySpeed_LowSpeedRange);
RUN_TEST(test_fuzzifySpeed_AtBoundaryLowToMedium);
RUN_TEST(test_fuzzifySpeed_MediumRange);
RUN_TEST(test_fuzzifySpeed_AtBoundaryMediumToHigh);
RUN_TEST(test_fuzzifySpeed_HighRange);
// fuzzifyDistance tests
RUN_TEST(test_fuzzifyDistance_CloseBelow8);
RUN_TEST(test_fuzzifyDistance_BetweenCloseAndMedium);
RUN_TEST(test_fuzzifyDistance_MediumRange);
RUN_TEST(test_fuzzifyDistance_FarRange);
// fuzzifyRoadCondition tests
RUN_TEST(test_fuzzifyRoadCondition_AtZero);
RUN_TEST(test_fuzzifyRoadCondition_AtOne);
RUN_TEST(test_fuzzifyRoadCondition_Middle);
// defuzzifyBrakeForce tests
RUN_TEST(test_defuzzifyBrakeForce_SingleRule);
RUN_TEST(test_defuzzifyBrakeForce_MultipleRules);
9. Conclusions
This paper illustrates the implementation of a fuzzy logic controller (FLC) on an STM32 microcontroller to simulate a vehicle proximity detection system. By utilizing inputs from an ultrasonic sensor, the system assesses the distance to obstacles while factoring in road conditions and vehicle speed.
Fuzzy logic is used to manage the inherent uncertainty and imprecision in sensor data, emulating human reasoning. The system processes inputs through fuzzification, evaluates rules using linguistic terms (such as “Close,” “Medium,” “Far”), and determines an appropriate brake force through defuzzification. Communication with other simulated vehicle systems is enabled via the CAN protocol, facilitating integration into broader automotive applications.
The fuzzy logic controller provides substantial benefits over traditional crisp controllers by eliminating the need for precise mathematical models and demonstrating resilience against noisy sensor data. The system concurrently evaluates multiple fuzzy rules and calculates the brake force as a weighted average of their firing strengths. This process allows for smooth transitions between braking levels and ensures safe responses to varying road conditions. The overlapping membership functions for speed, distance, and road conditions enhance the controller’s adaptability, facilitating nuanced decisions in complex, real-world scenarios.
By successfully integrating fuzzy logic into an STM32-based system, this paper underscores the practical benefits of FLCs in a simulated automotive setting like the one presented. This implementation serves as a foundational model for ADAS in a simulated environment. The comparison with traditional crisp controllers highlights the flexibility and real-world applicability of fuzzy logic systems.
Future Work: While the current system effectively uses distance, speed, and road conditions as input variables, future work could explore the integration of additional sensory inputs like tire pressure or lateral acceleration to further enhance adaptability and precision [
21]. Additionally, incorporating sensor fusion techniques could improve the system’s performance in rapidly changing conditions and complex scenarios, as highlighted by ongoing research. These advancements have the potential to increase the accuracy of vehicle control and further optimize power distribution, paving the way for more sophisticated and efficient ADAS.