This is an old revision of the document!


Lab 3: NXP Cup Autonomous Car

Duration

2 hours:

  • 0h30 theoretical introduction to NXP Cup, vehicle dynamics, and PID control;
  • 1h30 practical tuning and modular firmware development.

Learning Objectives

After this laboratory, students should be able to:

  • Explain the data flow in an autonomous line-follower (sensors, control, actuators);
  • Describe the role of Proportional, Integral, and Derivative terms in a PID controller;
  • Tune a PID controller experimentally on physical or emulated hardware;
  • Implement and validate coordinate mapping algorithms for line tracking camera sensors;
  • Map abstract controller commands to physical servo PWM pulse widths.

Laboratory Scenario

The lab focuses on programming and tuning an autonomous line-following vehicle. The system utilizes a PixyCam2 camera for line detection, a PID controller for trajectory correction, and a steering servomotor.

``` [PixyCam2 Camera] → vector path → [Error Estimator (Ex 2)] → error → [PID Controller] → output → [Servo Command (Ex 3)] → PWM → [Steering Servo] ```

In each control loop iteration, the vehicle executes the following sequence:

1. Read the path vectors reported by PixyCam2.
2. Estimate the lateral steering error from the detected vector.
3. Compute the tracking error: error = 0.0f - estimated_error.
4. Apply the PID control algorithm to the tracking error.
5. Map the PID controller output to a physical servo command.
6. Adjust the motor speed profile based on path curvature and stability.
7. Write commands to the actuators (servo and ESC).
8. Wait for the next control cycle.

The vehicle does not know the track geometry in advance; it reacts dynamically to real-time measurements. If the line shifts left, it steers left; if it shifts right, it steers right; if the line is centered, the wheels remain straight.

Equipment Overview: The NXP Cup Platform

An NXP Cup autonomous vehicle consists of the following primary components:

Component Role Practical Engineering Challenges
Microcontroller Runs the real-time control loop sampling frequency, latency, memory constraints
PixyCam2 Detects path vectors in the image frame calibration, ambient light, lost vectors, intersections
Steering Servo Controls the front wheel angle mechanical limits, saturation, non-linear response
Motor / ESC Drives the vehicle's propulsion inertia, wheel slippage, current limits, battery sag
Encoder Measures real-time wheel speed missing pulses, quantization noise, sampling delay
Battery Powers the logic board and motors voltage drops, performance degradation under load

Controller Theory: PID

The PID controller computes the steering adjustment using three distinct terms:

Term Conceptual Formula Physical Effect
P - Proportional proportional to current error reacts quickly to immediate deviations from the line
I - Integral accumulates error over time corrects persistent steady-state offsets
D - Derivative proportional to error rate-of-change dampens overshoot and suppresses oscillations

The discrete implementation used in the vehicle firmware is:

integral = integral + error * dt;
derivative = (error - previous_error) / dt;
output = kp * error + ki * integral + kd * derivative;
previous_error = error;

After computing the output, it is saturated to the safety limits of the steering servo:

if (output > max_output) output = max_output;
if (output < min_output) output = min_output;

Project Layout

The laboratory package contains the following files:

  • pid_tuning/pid_config.txt - configuration file containing runtime PID parameters (Kp, Ki, Kd, speed);
  • pid_tuning/flash_car.sh - script for uploading the parameters to the vehicle;
  • exercise2_pixy_vector/pixy_vector.c - source file for the PixyCam2 coordinate error estimator (student TODO);
  • exercise2_pixy_vector/pixy_vector.h - header file defining the PixyVector structure and function signature;
  • exercise2_pixy_vector/test_pixy_vector.c - testbench for validating the error estimation;
  • exercise3_steering/steering.c - source file for the servo command converter (student TODO);
  • exercise3_steering/steering.h - header file defining the servo mapping function signature;
  • exercise3_steering/test_steering.c - testbench for validating the servo conversion;
  • Makefile - build system to compile and execute the test suites.

Students do not need to modify the full vehicle firmware. You will implement and validate the core modules locally, and then tune the PID parameters on the physical car.

Exercise 1: Experimental PID Tuning

Objective

Tune the kp, ki, and kd gains of the vehicle controller to achieve stable and fast line-following behavior on the physical track.

Materials

  • Pre-compiled vehicle binary running on the platform;
  • The editable pid_tuning/pid_config.txt parameter file;
  • The flashing script pid_tuning/flash_car.sh.

Example configuration file:

kp=0.35
ki=0.00
kd=0.08
speed=0.40

Procedure

  1. Start with the integral term disabled (ki = 0.00).
  2. Increase the proportional gain kp progressively until the car follows the line, but starts to oscillate left-and-right around the center.
  3. Increase the derivative gain kd to dampen the oscillations and smooth the vehicle's trajectory.
  4. Introduce a tiny integral gain ki only if the vehicle exhibits a persistent offset to one side (due to mechanical misalignment).
  5. Reduce the speed parameter if the vehicle spins out or loses the line in sharp curves.
  6. Record your experimental runs in the table below.

Tuning Recommendations

  • One Parameter at a Time: Alter only a single PID gain parameter between experimental runs to isolate the physical effect of each gain.
  • Safety First: Start testing at low speeds (e.g., speed=0.40) before attempting high-speed runs to prevent physical damage to the vehicle.
  • Handling Oscillations: If the vehicle exhibits high-frequency oscillations (wiggling), decrease kp or slightly increase kd.
  • Handling Sluggishness: If the vehicle reacts too slowly to curves and drifts wide, increase kp.
  • Handling Curve Instability: If the vehicle flies off the track in sharp turns, reduce speed or increase the steering controller gain.

Uploading to the Vehicle

Deploy the modified configuration using the flashing script:

./flash_car.sh pid_config.txt

Test the vehicle on the track and document your findings:

Run kp ki kd speed Observations
1
2
3
4

Questions & Observations

  • What physical behavior is observed when kp is too low?
  • What physical behavior is observed when kp is too high?
  • How does the vehicle's trajectory change as you increase kd?
  • Was an integral term ki necessary for stable tracking? Explain why.

Exercise 2: PixyCam2 Vector Error Estimation

Objective

Implement a C function that parses a raw tracking vector from PixyCam2 and returns a normalized steering error relative to the image frame center.

Theoretical Context

The PixyCam2 reports line tracking vectors in image coordinates. The $x$ coordinate increases from left to right, and the $y$ coordinate increases from top to bottom. To determine the immediate direction of the path, you must track the endpoint of the vector that is closest to the front of the car (the bottom of the image frame, which corresponds to the larger $y$ coordinate).

  • If $y_0 > y_1$, use $x_0$.
  • If $y_1 > y_0$, use $x_1$.
  • If the vector is horizontal ($y_0 == y_1$), use the average of $x_0$ and $x_1$.

The function must return a normalized error in the range [-1.0, 1.0]:

  • -1.0 represents the far-left edge of the frame;
  • 0.0 represents the exact center of the frame;
  • 1.0 represents the far-right edge of the frame.

If the input frame_width ⇐ 1, return 0.0f. Clamp the selected $x$ coordinate to the valid image boundaries $[0, \text{frame\_width} - 1]$ before normalization.

Recommended normalization formula:

center = (frame_width - 1) / 2.0
error = (x - center) / center

Examples for frame_width = 79

Vector Result Explanation
{39, 0, 39, 51} 0.0 Bottom endpoint is exactly in the center
{39, 0, 0, 51} -1.0 Bottom endpoint is at the far-left edge
{39, 0, 78, 51} 1.0 Bottom endpoint is at the far-right edge
{39, 0, 52, 51} approx. 0.333 Bottom endpoint is slightly to the right
{20, 20, 58, 20} 0.0 Horizontal vector: uses average x

Interface

Implement the function in exercise2_pixy_vector/pixy_vector.c:

typedef struct {
    int x0;
    int y0;
    int x1;
    int y1;
} PixyVector;
 
float estimate_pixy_vector_error(PixyVector vector, int frame_width);

Local Validation

Compile and run the local unit tests from the workspace:

cd nxp_car_lab_skeleton
make test-pixy

Exercise 3: Servo Command Conversion

Objective

Implement a C function to map the abstract floating-point PID controller output to a physical PWM pulse width in microseconds for the steering servomotor.

Theoretical Context

The PID controller produces an abstract output intended to represent steering direction. The function must:

1. Clamp the input `pid_output` to the safe operating range of ''[-1.0, 1.0]'', where ''-1.0'' represents maximum left steer and ''1.0'' represents maximum right steer.
2. Map this clamped value linearly to a standard servo PWM pulse width in the range ''[1000, 2000]'' microseconds, where ''1500'' microseconds represents the center position (wheels straight).

Recommended conversion formula:

servo_us = 1500 + pid_output * 500

Examples

pid_output Expected PWM (us)
-1.0 1000
-0.5 1250
0.0 1500
0.5 1750
1.0 2000
2.0 2000 (clamped)
-2.0 1000 (clamped)

Interface

Implement the function in exercise3_steering/steering.c:

int pid_output_to_servo_us(float pid_output);

Local Validation

Compile and run the local unit tests:

cd nxp_car_lab_skeleton
make test-steering

Deliverables

Upon completion of the laboratory, submit the following:

  • The tuned pid_config.txt configuration file;
  • Written answers to the theoretical questions in Exercise 1;
  • Your C implementations for exercise2_pixy_vector/pixy_vector.c and exercise3_steering/steering.c;
  • Terminal output logs or screenshots showing that both local test suites pass successfully.

Grading Criteria

Component Percentage
PID tuning analysis and track characterization 30%
Functional PID parameters on the physical track 25%
Exercise 2: PixyCam2 error estimation implementation 20%
Exercise 3: Servo command conversion implementation 15%
Code cleanliness, proper clamping, and local validation 10%

General Recommendations

  • Local Validation: Always verify your code implementations using the local test suites (make test) before deploying or tuning.
  • Code Quality: Write clean, self-documenting code, handle all safety clamping, and consider extreme edge cases (such as negative or zero frame width).
rasb/lab/03.1782470342.txt.gz · Last modified: 2026/06/26 13:39 by rares.sarmasag
CC Attribution-Share Alike 3.0 Unported
www.chimeric.de Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0