# [Final Project] Design and Implementation of a Line-Tracking and Material-Handling Robot System Based on LEGO EV3

## Abstract

This project designs and implements an intelligent line-tracking and material-handling robot based on the LEGO MINDSTORMS EV3 platform. To address the challenges of multi-intersection recognition, dynamic line tracking, and specific material grasping in complex track environments, this system introduces an improved discrete-time proportional-derivative (PD) control algorithm in the low-level motion control layer. Combined with a differential-drive kinematic model, the system achieves smooth and adaptive trajectory tracking. At the macro path-planning and task-execution level, a deterministic decision tree model based on Boolean logic and a finite-state machine (FSM) is constructed, solving typical engineering problems such as "sensor blinding," "intersection misjudgment," and "false positive endpoint detection." This paper elaborates on the control theory foundation, mathematical derivation of the algorithm, hardware-software co-design, and compares the performance of different controllers on straight lines, ellipses, and figure-8 complex trajectories in the context of control theory history and related empirical studies. Furthermore, low-level computational optimization strategies are proposed for the physical characteristics of embedded systems (e.g., CPU starvation, PWM control response)$^{[1]}$.

## 1. Introduction

In the field of mobile robotics, line tracking and autonomous navigation form the foundation for accomplishing complex tasks. The core challenge lies in designing a reliable controller capable of handling dynamic environments and hardware constraints. In early automatic control development, simple on-off control (Bang-Bang or ON-OFF control) was commonly adopted. However, this "all-or-nothing" control logic often leads to severe trajectory oscillation, significant mechanical wear, and a high tendency to derail at high speeds. Since a two-wheel differential-drive robot is a typical non-holonomic constraint system with zero lateral velocity, it can only adjust lateral deviation through yaw angular velocity, placing extremely high demands on the smoothness and precision of steering commands$^{[1]}$.

To improve the robustness and dynamic response of the system, this project introduces the widely used PID (Proportional-Integral-Derivative) closed-loop control algorithm from industrial practice$^{[2]}$. The history of PID control theory can be traced back to governor designs in the 1890s, and it was first rigorously analyzed mathematically in 1922 by Russian-American engineer Nicolas Minorsky while designing automatic ship steering systems for the U.S. Navy$^{[2]}$. By observing the actions of helmsmen, Minorsky discovered that effective control requires not only consideration of the current error but also the accumulated past error and the trend of error change$^{[2]}$. Building on this foundation, this study combines LEGO EV3's multi-photosensor fusion technology to discretize and dimensionally reduce the traditional PID controller, achieving adaptive line tracking. Related empirical studies have shown that deploying a PID controller on a LEGO EV3 robot can effectively eliminate high-frequency chassis oscillations and improve tracking efficiency and stability on complex tracks$^{[1]}$.

LEGO MINDSTORMS EV3 is the third-generation robotics kit from LEGO. Its core programmable brick features an ARM9-based TI Sitara AM1808 processor clocked at 300 MHz, running a lightweight Linux operating system$^{[3]}$. EV3 supports various sensors (color sensors, ultrasonic sensors, gyroscopes, etc.) and servo motors, and can be programmed using LabVIEW graphical programming environment or high-level languages such as MicroPython$^{[3]}$. These hardware characteristics provide the foundation for deploying control algorithms.

## 2. Core Low-Level Algorithm: Differential Kinematics and Improved PD Control

The core of line-tracking control lies in using the luminous flux feedback from color sensors to compute the deviation of the robot body from the guide line in real time and convert it into dynamic differential speed for the left and right drive wheels, thereby generating a corrective torque. This project adopts a hardware layout with two color sensors straddling the line and constructs a digital PD controller adapted to the sampling characteristics of the embedded microprocessor.

### 2.1 Kinematic Model of Differential-Drive Robots

Before establishing the control algorithm, the kinematic chassis characteristics of the robot must be clarified as the physical basis for control output. Let the linear velocities of the left and right drive wheels be $V_L$ and $V_R$, respectively, the distance between the two wheel centers (wheel track) be $d$, and the drive wheel radius be $r$. According to the non-holonomic kinematic model of wheeled mobile robots, the overall linear velocity $V$ and yaw angular velocity $\omega$ of the robot's center of mass can be derived from the following equations$^{[2]}$:

$$V(t) = \frac{V_R(t) + V_L(t)}{2}$$

$$\omega(t) = \frac{V_L(t) - V_R(t)}{d}$$

From this mathematical model, it is evident that by applying equal-magnitude, opposite-direction differential compensation to the left and right wheels (i.e., changing the relative magnitudes of $V_L$ and $V_R$), the yaw angular velocity $\omega$ of the robot can be linearly controlled. This differential compensation constitutes the required steering torque and serves as the dynamic foundation for correcting the robot's posture.

### 2.2 Mathematical Derivation of the Discrete-Time PID Control Algorithm

The classical PID control equation in the continuous-time domain computes the control output through proportional, integral, and derivative operations on the error. Its standard formula is expressed as$^{[2]}$:

$$u(t) = K_p e(t) + K_i \int_{0}^{t} e(\tau) d\tau + K_d \frac{de(t)}{dt}$$

where $K_p, K_i, K_d$ are the proportional gain, integral gain, and derivative gain, respectively, and $e(t)$ is the error between the system setpoint and feedback$^{[2]}$.

However, the EV3's main processor (ARM9) is a digital embedded system based on discrete-time sampling and cannot directly handle continuous calculus operations. Therefore, we need to discretize the above continuous equation using the finite difference method. Assuming a constant sampling period $\Delta t$ for the microprocessor and an error $E(k)$ at the $k$-th sampling instance, according to the backward finite difference principle, the first-order derivative can be approximated by the difference equation $\frac{E(k) - E(k-1)}{\Delta t}$, and the integral term can be approximated by the discrete accumulation sum $\sum_{j=0}^{k} E(j) \Delta t$. This yields the positional-form digital PID equation$^{[2]}$:

$$U(k) = K_p E(k) + K_i \sum_{j=0}^{k} E(j) \Delta t + K_d \frac{E(k) - E(k-1)}{\Delta t}$$

In the symmetric dual-photosensor line-tracking scenario, the curvature of the guide line changes rapidly. If the integral term $I$ is retained, when the setpoint undergoes large changes (e.g., sharp curves), the integrator accumulates excessive error. This may cause the control output to be truncated by upper and lower limits, resulting in "Integral Windup." This phenomenon manifests as the output remaining at the saturation upper limit, unable to respond in time even when the error sign changes, ultimately leading to overshoot or the robot running off the track. Therefore, this project performs dimensionality reduction optimization on the traditional model by discarding the integral term and implicitly incorporating the constant sampling period $\Delta t$ into the coefficients, resulting in the discrete digital PD controller$^{[2]}$:

$$U(k) = K_p \cdot E(k) + K_d \cdot [E(k) - E(k-1)]$$

### 2.3 System-Level Mapping and Parameter Analysis of the Steering Compensation Algorithm

In the actual software code of the project, the following steering compensation (Turn) operation equation is implemented through nested advanced mathematical modules:

$$Turn = (a-b) \times 0.8 + ((a-b)-c) \times 0.6$$

This equation corresponds to the discrete digital PD equation derived above. First, regarding the acquisition of the error signal, $a$ represents the reflected light intensity digital value from the left sensor, and $b$ represents that from the right sensor. Based on the principle of diffuse reflection, the current error signal $E(k) = a - b$. When the robot is centered, both left and right sensors are at the black-white boundary with similar light absorption rates, resulting in $a-b \approx 0$. If the robot deviates to the right, the left sensor enters the white high-reflectance area while the right sensor enters the black low-reflectance area, generating a positive error signal.

Second, the term $(a-b) \times 0.8$ in the equation corresponds to the proportional control term. Proportional control considers only the current error, producing a restoring torque proportional to the current deviation. The proportional gain $K_p = 0.8$ determines the system's response strength to disturbances — the larger the deviation, the stronger the corrective torque output.

Finally, the term $((a-b)-c) \times 0.6$ in the equation maps to the derivative control term, where $c$ represents the historical error $E(k-1)$ from the previous cycle stored in a register. The derivative control term acts as the system's damper; it computes the first derivative of the error to predict future trends. When the robot approaches the centerline under the action of proportional control, although the current position error $E(k)$ is still greater than zero, its rate of change $\Delta E(k)$ has already become negative. At this point, the derivative term generates an opposing braking torque in advance, reducing the total control output, thereby suppressing overshoot and oscillation in the underdamped system. $K_d = 0.6$ is the derivative damping coefficient determined after system tuning. It should be noted that ideal differentiators are sensitive to high-frequency noise; however, due to the relatively high sampling frequency of this system and the error source being only the difference between two light intensity values, no additional low-pass filter was introduced.

### 2.4 Dynamic Adaptive Base Speed Nonlinear Model

Traditional line-tracking robots often use a constant base speed. However, in composite tracks containing both straight sections and curves, the base speed needs to be dynamically adjusted according to the path curvature. This project introduces an adaptive speed feedback regulation model based on the absolute value of the error:

$$BaseSpeed = 100 - |a-b| \times 0.6$$

This equation establishes a nonlinear negative feedback mapping function $f(|e|)$. The constant $100$ represents the maximum PWM duty cycle allowed for the chassis motor under the current supply voltage. When in steady-state straight-line travel, the robot is centered, resulting in a small position error ($|a-b| \approx 0$), and the base speed approaches the upper limit of $100$, enabling fast straight-line movement. When encountering curves, the absolute error increases, and the system automatically reduces the base speed through negative feedback, decreasing the centripetal force required for turning and reducing the risk of sideslip.

It is worth noting that the constant term (100) in this formula differs from the constant (80) in earlier versions. After multiple rounds of field testing and parameter tuning, raising the base speed upper limit to 100 improves the average travel speed on straight sections without sacrificing curve stability. The error attenuation coefficient of $0.6$ was calibrated to balance speed reduction and steering requirements.

### 2.5 Unified Mathematical Expression of the Complete Control Law and Python Simulation Verification

Combining the two core formulas above yields the complete discrete-time PD control law used in this project:

$$\begin{aligned}
BaseSpeed(k) &= 100 - |E(k)| \times 0.6 \\
Turn(k) &= E(k) \times 0.8 + [E(k) - E(k-1)] \times 0.6 \\
LeftPWM(k) &= BaseSpeed(k) - Turn(k) \\
RightPWM(k) &= BaseSpeed(k) + Turn(k)
\end{aligned}$$

where $E(k) = a(k) - b(k)$ is the error signal of the current sampling cycle, and $E(k-1)$ is the historical error of the previous cycle. The left and right wheel PWM commands are obtained through a linear combination of the base speed and steering compensation. When $Turn > 0$, the left wheel decelerates and the right wheel accelerates, achieving a left turn; conversely, a right turn is achieved.

To verify the convergence characteristics of this control law, we built a discrete-time simulation system based on Python. This simulation system models the following physical elements:

1. **Circular sensor detection model**: The detection area of each color sensor is modeled as a circular area with a diameter of 1.5 cm. The overlap area between this circular area and the black guide line (width 2.0 cm) is computed through numerical integration to accurately calculate the reflected light intensity reading$^{[1]}$.
2. **Differential-drive kinematics**: Based on EV3 standard wheel geometry parameters (wheel track 12.0 cm, wheel radius 2.8 cm), PWM commands are mapped to forward velocity and yaw angular velocity.
3. **Trailing sensor layout**: The sensor axis is located 10.0 cm ahead of the drive wheel axis. This "trailing" configuration introduces a lever-arm effect, which is one of the causes of oscillatory dynamic behavior.
4. **Gaussian measurement noise**: Gaussian white noise with a standard deviation of 0.3 is superimposed on the sensor readings to simulate optical interference in real environments.

The simulation initial conditions are set as follows: initial yaw angle $+10^\circ$ (tilted to the right), left sensor reading $a=10$ (fully over the black line), right sensor reading $b=50$ (half over the black line edge). Simulation time step $\Delta t = 0.1$ s.

EV3 Line-Tracking Robot — Discrete-Time PD Simulation

**Figure 1: EV3 Line-Tracking Robot — Discrete-Time PD Control Simulation Results**

Figure 1 presents the time-domain evolution curves of four sets of key physical quantities:

**Panel (a) — Sensor Reflectance and Error Signal**: The readings of the left sensor $a(t)$ (red) and right sensor $b(t)$ (blue) over time. At the initial moment, $a=10$ (fully black), $b=50$ (half black, half white), with error $e(t)=a-b=-40$. As the PD controller intervenes, the error signal converges rapidly to near zero within approximately 5 seconds, followed by small fluctuations around zero. This convergence behavior validates the steady-state tracking capability of the PD control law.

**Panel (b) — PD Control Signals**: The time-domain curves of base speed $BaseSpeed(t)$ (green) and steering compensation $Turn(t)$ (red). The large initial error causes the base speed to drop to $100 - 40 \times 0.6 = 76$, while the steering compensation produces a large negative value ($Turn \approx -40 \times 0.8 + (-40-0) \times 0.6 = -56$), driving the right wheel to accelerate and the left wheel to decelerate, generating a left corrective torque. As the error converges, the base speed returns to near 100, and the steering compensation approaches zero, with the system entering steady-state straight-line mode.

**Panel (c) — Robot Pose and Oscillatory Convergence**: The time-domain curves of yaw angle $\theta(t)$ (orange), lateral offset $y(t)$ (purple), and yaw angular velocity $\omega(t)$ (blue). This is the core panel for verifying the damping characteristics of the PD controller. The initial $+10^\circ$ yaw angle exhibits typical underdamped second-order system response characteristics under PD control — converging to zero after approximately 2-3 cycles of decaying oscillation. The lateral offset $y(t)$ also shows an oscillatory convergence trend, eventually stabilizing near the guide line center. The amplitude of the yaw angular velocity $\omega(t)$ decreases over time, indicating that the system's kinetic energy is effectively dissipated by the derivative damping term.

**Panel (d) — Zoomed View of Yaw Angle Oscillation (First 10 Seconds)**: This panel uses scatter plots to mark the yaw angle at each discrete sampling instant, clearly showing the step-by-step correction process of the PD controller at each time step. This "stepping" correction trajectory is a characteristic feature of discrete-time control systems — the controller computes new PWM commands based on the current error at each sampling cycle, driving the robot's posture to gradually approach the target.

**Panel (e) — Top-Down Trajectory**: The trajectory of the wheel axis center on the 2D plane. The semi-transparent black strip represents the guide line with a width of 2.0 cm. The trajectory curve shows that the robot, after departing from the starting point (green square), quickly converges to the guide line through an S-shaped path, then proceeds stably along the straight line to the end point (red square). The smoothness of the trajectory intuitively reflects the tracking accuracy of the PD controller.

These simulation results theoretically verify that the PD control law of this project can converge the initial $+10^\circ$ yaw angle error to zero within approximately 5 seconds, with a steady-state error controlled within $\pm 0.5^\circ$. This convergence speed and accuracy provide a theoretical basis for subsequent field testing.

## 3. Macro Path Planning: Finite-State Machine and Decision Tree Algorithm

In machine learning and decision analysis theory, a decision tree is a special tree-structured predictive model that represents the mapping relationship between object attributes and object values. It creates an optimal plan for reaching a goal by calculating conditional probabilities or setting decision rules$^{[4]}$. On the basis of the low-level PD algorithm ensuring basic trajectory continuity, the robot must possess high-level logic capabilities for handling complex maze topology and specific interaction tasks. This project uses nested switches to construct a deterministic decision tree based on state transitions, ensuring logical rigor and robustness.

To clarify the strategies related to material handling in the experiment, the program introduces simple randomization and counting variables during initialization: a total of two barrels are placed, with barrel positions numbered 1, 2, 3, 4 among four candidate locations. During initialization, one position is randomly selected from each of the sets {1,2} and {3,4}, thereby determining the positions of the two barrels to be grasped (avoiding a fixed pattern where both barrels are on the same side). During program execution, a Boolean variable `HasBarrel` indicates whether a barrel is currently being carried; an integer variable `BarrelNum` (initial value 0) records the number of barrels grasped, incremented by 1 each time a barrel is grasped; an integer variable `CheckNum` (initial value 0) records the number of red checkpoints passed, with the elapsed time for each checkpoint output on the corresponding line of the screen each time a checkpoint is passed.

### 3.1 Boolean Logic-Based Finite-State Machine and Sensor Blinding Protection

In automatic material handling tasks, the robot relies on an ultrasonic sensor to detect target barrels and execute grasping. After the grasping action is completed, the material typically remains in front of the sensor, which may cause the ultrasonic ranging reading to continuously satisfy the trigger condition, leading to the "sensor blinding" problem of repeated grasping. To solve this problem and meet the experimental requirement of a two-barrel placement strategy, this project introduces the following variables into the finite-state machine: Boolean variable `HasBarrel` (indicating whether a barrel is currently being carried), integer counter `BarrelNum` (recording the number of barrels grasped, initial value 0), and integer counter `CheckNum` (recording the number of red checkpoints passed, initial value 0).

The trigger condition for the grasping logic remains primarily based on ultrasonic distance:

$$Trigger = (d_{ultrasonic} < 15) \land \neg HasBarrel$$ When the grasping action is executed and confirmed successful, the program executes `HasBarrel = True` and `BarrelNum += 1`. According to the placement strategy agreed upon by the group: the first barrel grasped (`BarrelNum == 1`) should be placed at the first red checkpoint encountered thereafter; the second barrel grasped (`BarrelNum == 2`) should be carried all the way to the end point and then released. Therefore, when reaching a checkpoint, the condition for releasing the barrel is `HasBarrel == True && BarrelNum == 1`; if `HasBarrel == True` but `BarrelNum != 1`, only the turn-around or corresponding intersection action is performed without releasing the barrel. After completing the barrel release, `HasBarrel` is reset to False. ### 3.2 Intersection Decision Algorithm Based on Finite-State Machine When facing branching tracks (such as T-junctions or cross intersections), the system adopts a deterministic decision tree based on a finite-state machine for path selection. This decision tree is implemented through nested conditional branches, and its internal logic can be precisely tested and verified. The specific execution flow is as follows: When the left and right sensors detect reflected light intensity below the threshold (< 15), the system determines that it may have entered an intersection area. The system first performs a probe verification: for right sensor triggering, the motors move forward at power 30 for 0.55 seconds for position adjustment, then execute a right turn at 30/-30 power for 0.3 seconds, maintaining this differential speed until the middle sensor detects the black line (reflected light intensity < 15), finally stopping the motors and waiting 0.02 seconds for stabilization. For left sensor triggering, the motors first move forward at power 30 for 0.5 seconds, then execute a left turn at -30/30 power for 0.3 seconds, maintaining this differential speed until the middle sensor detects the black line. If neither the left nor right sensor is triggered but the middle sensor detects the black line, the system enters the default PID straight-line logic. If the middle sensor detects a red marker, a 180-degree turn-around operation is executed. ### 3.2.1 Final Version of Intersection Decision and Material Placement Logic (Implementation Notes) This section explains the specific implementation details of the group's final program to avoid ambiguity between the more general decision tree description in the text and the final code. Key points are as follows (the code implementation takes precedence): 1. During initialization, two barrel placement positions are randomly selected from four candidate locations (numbered 1, 2, 3, 4): one position is randomly selected from each of the sets {1,2} and {3,4}, determining the positions of the two barrels to be grasped. 2. Variables used: Boolean `HasBarrel` (whether carrying a barrel), integer `BarrelNum` (barrel grasp count, initial 0), integer `CheckNum` (checkpoint count, initial 0). When grasping is successful, execute `HasBarrel = True; BarrelNum += 1`. 3. Placement strategy: The first barrel grasped (`BarrelNum == 1`) is released at the first red checkpoint encountered; the second barrel grasped (`BarrelNum == 2`) is carried all the way to the end point and released there. Therefore, the condition for triggering barrel release when reaching a checkpoint is `HasBarrel == True && BarrelNum == 1`. After releasing, `HasBarrel` is reset to `False`. 4. The maze traversal strategy adopts the right-hand rule: turn right if possible; if not, go straight; if not, turn left. Since the sensors are placed side by side and can only perceive left/right and the color/reflectance beneath, the flow is prioritized in the program as follows: - If the middle sensor detects green: determined as the end point, exit the main loop and execute the end-point procedure. - If the middle sensor detects red: determined as a checkpoint, execute `CheckNum += 1` and output the elapsed time for that checkpoint on the corresponding line of the screen; if `HasBarrel == True && BarrelNum == 1` is satisfied, release the barrel and turn around; otherwise, only turn around. - Otherwise, if the right sensor's reflectance is less than 15 (detecting the black line), directly execute the right-turn logic. - Otherwise, if the left sensor detects the black line, first probe forward a small step and re-read the middle sensor: if the middle sensor detects the black line after probing, go straight; if not, turn left. - If none of the above conditions are triggered, enter the default PD line-tracking logic. 5. The PD line-tracking default parameters in the code are implemented as follows: $$BaseSpeed = 100 - |a-b| * 0.6$$ $$Turn = (a-b) * 0.8 + ((a-b) - c) * 0.6$$ where `a` and `b` are the left and right sensor readings, and `c` is the error register from the previous cycle. This subsection provides the implementation notes for the final version of the program. The decision tree and probe timing descriptions elsewhere in the text are general references; the actual behavior is governed by the logic described in this section. ### 3.3 End Point Recognition: Heterogeneous Sensor Decoupling and Software Debouncing In early test versions, the end point determination logic (detecting the black end zone) and the intersection determination logic (detecting the black line) used the same reflectance grayscale features, which could lead to misjudgment due to threshold drift caused by ambient light. To solve this problem, the system designates a green sticker as the end point marker, identified by the centrally positioned third sensor using Color Mode, achieving sensor-level separation between navigation and end point determination. Additionally, to prevent false triggering by the green marker in the starting area, a timer constraint is added: $$Condition_{End} = (\text{Color}_{Mid} == 3) \land (\text{Timer}_{Total} > 10s)$$

After the color determination passes, the program also adds a 0.1-second software debounce delay to ensure a stable green signal is obtained before triggering the end point stop.

When reaching the end point, the screen sequentially displays the elapsed time for each checkpoint, the total time, and the number of checkpoints visited. In the code implementation, `CheckNum` is used to determine the display line, and the corresponding elapsed time is written immediately when passing each checkpoint.

Figure 2 shows a screenshot of the complete program code implemented in the LEGO EV3 graphical programming environment, which implements the finite-state machine and decision tree logic described above. The program source file is main.ev3.

EV3 Program Source Code Screenshot

**Figure 2: EV3 Graphical Program Source Code.** The program implements path planning and material handling control logic based on a finite-state machine, comprising three stages: initialization, main loop (intersection decision, grasping/placement, end point determination), and termination.

## 4. Embedded System Low-Level Characteristics and Computational Optimization

The underlying firmware of the LEGO EV3 runs in a lightweight Linux operating system environment. Its graphical interface is essentially a wrapper around the underlying hardware abstraction layer (HAL)$^{[3]}$. In closed-loop control systems requiring millisecond-level real-time response, improper code structure may cause system-level resource issues. This program implements software engineering-level optimizations to address these concerns.

### 4.1 CPU Starvation Prevention

In the main loop (While Loop), without intervention, high-frequency instruction execution may occupy most of the ARM processor's clock cycles, causing the underlying I/O polling daemon to be suspended — a phenomenon known as "CPU starvation." The direct consequence is that sensor data registers cannot be updated in time, and the PID controller reads stale data, leading to abnormal motor control. To address this, a 0.01-second wait (Yield/Delay) module is inserted at the end of the main loop, actively yielding the processor's scheduling time slice to allow the underlying I/O processes to refresh the sensor registers normally.

### 4.2 PWM Output Mode Optimization (Coast vs Brake)

If the motor drive module is set to "run for a specified time" mode, the underlying hardware driver will forcibly trigger electrical braking (short-circuiting the motor windings) when the time threshold is reached. Frequent braking can cause high-frequency jitter in the robot body. It should be noted that our implementation does not adopt the continuous "On" mode, because the "On" mode would prevent the main controller from returning to the main loop in time to process other logic (such as sensor readings, state updates, and decision-making) while the motor is being driven, posing a risk of system "freezing" due to blocking. To balance continuous output and schedulability, we adopted a short-step drive strategy: PD line tracking operates with a 0.1-second cycle, driving the motor for only 0.1 seconds at a time (i.e., small steps forward), then returning to the main loop for sensor reading and logic judgment. This approach avoids the jitter problem caused by frequent braking while ensuring the system can respond to other events and state changes in a timely manner.

### 4.3 Process Management and Shutdown Procedure

In a program architecture that frequently calls audio files for status feedback, abnormal physical forced shutdown may cause anomalies in the underlying audio daemon. The system introduces a standardized shutdown procedure after the end point determination branch, ensuring safe power-off of sensor and motor ports and proper destruction of background threads through the stop module, thereby ensuring system stability in multi-round continuous operation environments.

## 5. Experimental Results and System Performance Analysis

To verify the actual comprehensive performance of the designed "improved discrete PD controller + finite-state machine decision tree" hybrid control architecture on the LEGO Mindstorms EV3 platform, we conducted multiple rounds of performance testing on the test field and performed comparative analysis with the traditional ON-OFF switch controller.

### 5.1 Experimental Environment and Track Characteristics

The test track for this project consists of long straight sections, pure right-angle turns, T-junctions, and cross-intersection maze segments assembled together. Right-angle turns correspond to discontinuous step signals in the trajectory equation where derivatives do not exist. For tracks containing such step signals, a purely linear PD controller alone cannot independently cover the entire track; it requires collaborative processing with the underlying digital PD controller and the finite-state machine-based decision tree.

Figure 3 shows a grid map drawn according to the track layout, where black areas represent the guide path, white areas represent empty space, the start point is located in the lower-right area, and the end point is located in the upper-left area. The track includes various road conditions such as long straight sections, right-angle turns, T-junctions, and cross intersections.

Test Track Grid Map (29×29 Grid)

**Figure 3: Test Track Grid Map.**

### 5.2 Straight-Line Dynamic Response and Steady-State Error Analysis

In straight-line trajectory tracking tests, the robot using the ON-OFF switch controller exhibited significant periodic oscillation. The switch controller only adjusts direction left or right based on the binarized sensor results, causing the robot body to oscillate repeatedly on both sides of the guide line, resulting in a relatively low average forward speed.

After adopting the discrete PD controller, the oscillation amplitude of the robot body was significantly reduced. The derivative compensation term generates an opposing damping torque in advance based on the error change rate, suppressing the overshoot phenomenon. According to the control law shown in Equation (2.5), the base speed is adaptively adjusted based on the absolute error: in steady-state straight-line conditions, $|a-b| \approx 0$, and the base speed approaches the upper limit of 100; when deviation occurs, the base speed automatically decreases to reduce the centripetal force required for turning. Referring to comparative measurements in similar hardware conditions from related literature, the average forward speed on straight sections improved by approximately 36% after introducing the PD control mechanism$^{[1]}$.

### 5.3 Decision Tree Control and Execution Performance at Right-Angle Turns

In $90^\circ$ right-angle turn tests, the ON-OFF controller or pure PID controller exhibited tracking lag or ran off the track due to their inability to handle the step change in reflectance. This system uses a finite-state machine decision tree to handle such intersections. The specific execution flow is as follows:

When the left and right sensors detect reflected light intensity below the threshold (< 15), the system determines that it may have entered an intersection area. The system first performs a probe verification: for right sensor triggering, the motors move forward at power 30 for 0.55 seconds, then execute a right turn at 30/-30 power for 0.3 seconds, maintaining this differential speed until the middle sensor detects the black line (reflected light intensity < 15), finally stopping the motors and waiting 0.02 seconds for stabilization. For left sensor triggering, the motors first move forward at power 30 for 0.5 seconds, then execute a left turn at -30/30 power for 0.3 seconds, maintaining this differential speed until the middle sensor detects the black line. If neither the left nor right sensor is triggered but the middle sensor detects the black line, the system enters the default PID straight-line logic. After completing the turn, control is handed back to the PD controller to continue straight-line tracking. This process achieves deterministic control of right-angle turns through state transitions in the finite-state machine. ### 5.4 Overall Completion Rate and System Robustness In comprehensive tests incorporating material handling tasks, the system exhibited the following characteristics: 1. **CPU Starvation Prevention**: A 0.01-second wait module is inserted at the end of the main loop, actively yielding the processor's scheduling time slice to ensure the underlying I/O processes can refresh the sensor registers normally, avoiding sensor data freezing caused by CPU resource monopolization. 2. **Sensor Blinding Protection**: A global Boolean state variable `HasBarrel` is used to construct a finite-state machine. The ultrasonic sensor's grasping trigger condition is `(distance < 15cm) AND (NOT HasBarrel)`. After grasping is completed, the state is flipped. Even if the material subsequently blocks the ultrasonic sensor, the system will not repeatedly execute the grasping sequence but will instead enter the normal line-tracking logic. 3. **End Point Recognition**: The middle color sensor is used in Color Mode to identify a green sticker as the end point marker. Combined with a 0.1-second software debounce and a timer constraint (Timer > 10s), this achieves differentiation from the starting area green marker and reliable end point determination.

4. **Motor Control Optimization**: To balance continuous tracking and event response, our group adopted a short-step drive strategy: PD line tracking operates with a 0.1-second basic cycle, issuing only 0.1-second drive commands to the motors at a time (small steps forward), then returning to the main loop for sensor reading and logic judgment. This approach avoids the risk of main loop blocking (which would prevent timely processing of sensor and state transitions) associated with continuous "On" motor mode, while also reducing mechanical jitter caused by frequent timed braking.

In multiple rounds of testing, the system was able to complete the full-track line-tracking and material handling tasks in most cases. However, issues such as sensor blinding and color sensor misidentification still occurred during operation. Overall, these problems were mostly caused by sensor hardware characteristics or environmental changes (e.g., lighting); the software logic, after multiple rounds of verification, was deemed robust and recoverable, successfully completing the designated tasks in most tests.

### 5.5 Full Track Field Test Results

To verify the complete operational performance of the system on the actual track, we conducted field tests in both forward and reverse directions on the track shown in Figure 3. The track features a total of 6 red sticker checkpoints (triggering 180-degree turn-around and barrel release operations), with 3 checkpoints passed in each direction.

#### 5.5.1 Forward Direction Test Results

The robot departs from the starting point, travels forward along the guide path, sequentially passes through 3 red checkpoints, completes the corresponding turn-around and barrel release operations, and finally reaches the end point.

The total runtime was **54.92 seconds**, passing through **3** checkpoints. The elapsed times at each checkpoint were: **18.43 seconds, 29.13 seconds, 41.81 seconds**.

#### 5.5.2 Reverse Direction Test Results

The robot departs from the end zone, travels in reverse along the guide path, sequentially passes through the other 3 red checkpoints, completes the corresponding turn-around and barrel release operations, and finally reaches the starting area.

The total runtime was **51.34 seconds**, passing through **3** checkpoints. The elapsed times at each checkpoint were: **3.066 seconds, 24.54 seconds, 39.42 seconds**.

#### 5.5.3 Experimental Videos

The following videos document the complete operation process in both forward and reverse directions.

**Forward Direction Operation Video:**


https://www.youtube.com/watch?v=aTVxu1YXmjs
**Video 1: Full Track Forward Direction Operation Recording**

**Reverse Direction Operation Video:**


https://www.youtube.com/watch?v=Uk0Ih7O7AaE
**Video 2: Reverse Direction Full Track Operation Recording**

#### 5.5.4 Robot Hardware Design

The LEGO EV3 robot hardware design used in this system is shown in Figure 4. The robot adopts a two-wheel differential-drive chassis, with two reflected light sensors mounted at the front for line tracking, a color sensor in the middle for end point recognition and red marker detection, and an ultrasonic sensor at the front for material distance measurement.

EV3 Line-Tracking and Material-Handling Robot

**Figure 4: LEGO EV3 Line-Tracking and Material-Handling Robot Hardware Platform**

## 6. Conclusion

This project combines a discrete PD control algorithm, Boolean logic, and a finite-state machine to construct an autonomous line-tracking and material-handling system based on the LEGO EV3 platform. In low-level motion control, adaptive trajectory tracking of the guide line is achieved through a discretized PD controller. In macro path planning, deterministic control of multi-intersection navigation, material grasping and placement, and end point recognition is achieved through a finite-state machine. Additionally, low-level optimizations are implemented for embedded system issues such as CPU starvation and motor braking jitter. Experimental results demonstrate that the system can stably complete tracks containing right-angle turns, T-junctions, and material handling tasks, providing a reference for advanced development on the LEGO EV3 platform.

## References

[1] A. Stephan, N. Karthick Pugalum Perumal, M. Shivram Kumar, C. Akash, L. Varatharajan and M. Sivapalanirajan, "Performance Analysis of LEGO Mindstorm EV3 Robot with PID Controller for Trajectory Tracking Application," 2023 7th International Conference on Intelligent Computing and Control Systems (ICICCS), Madurai, India, 2023, pp. 1782-1787, doi: 10.1109/ICICCS56967.2023.10142757.

[2] Wikipedia contributors. (2026, May 25). PID controller. In Wikipedia, The Free Encyclopedia. Retrieved 05:44, May 27, 2026, from https://en.wikipedia.org/w/index.php?title=PID_controller&oldid=1356013976

[3] Wikipedia contributors. (2026, May 18). Lego Mindstorms EV3. In Wikipedia, The Free Encyclopedia. Retrieved 05:45, May 27, 2026, from https://en.wikipedia.org/w/index.php?title=Lego_Mindstorms_EV3&oldid=1354810351

[4] Wikipedia contributors. (2026, April 14). Decision tree. In Wikipedia, The Free Encyclopedia. Retrieved 05:49, May 27, 2026, from https://en.wikipedia.org/w/index.php?title=Decision_tree&oldid=1348906127

[5] Wikipedia contributors. (2026, May 24). Finite-state machine. In Wikipedia, The Free Encyclopedia. Retrieved 05:50, May 27, 2026, from https://en.wikipedia.org/w/index.php?title=Finite-state_machine&oldid=1355883596

This author has not provided a description.
Last updated on 2026-06-05