Programming · Hardware · Autonomous
🧰 Engineer Intermediate All Roles

Distance Sensor
Auton Correction

Use the V5 distance sensor to reset your robot's position against the wall before and during autonomous — eliminating drift, battery variance, and placement error.

Why Auton Fails Without It
The three reasons your autonomous drifts — and why a sensor fixes all three.

Even a perfectly tuned autonomous will drift at competition. Three forces work against you every match:

01

Battery Voltage

A fully charged battery drives faster than one at 70%. If your autonomous times out by distance or time, a low battery means the robot stops short — every time.

02

Floor Variation

Competition fields flex slightly under robot weight. The foam tiles at one event are not identical to your practice field. Small differences compound over a full autonomous route.

03

Placement Error

Drivers place the robot slightly differently every match — 1–2cm off, rotated a few degrees. At 12 feet of field, even 2° of heading error means the robot ends up 5+ inches from its target.

The fix: Before (or during) autonomous, drive to a known wall surface and use the distance sensor reading to correct your robot's exact position — regardless of battery, floor, or placement.

What "Wall Reset" Means

The distance sensor measures how far the robot is from the wall. If you know your robot should be exactly 300mm from the side wall at a given point in your route, you can use that reading to:

⚠️
Before this guide: You should be comfortable with EZ Template chassis functions and have a working autonomous routine. Read Sensor-Based Autonomous and Odometry first.
How Wall Reset Works
The concept, the math, and when to use it in a route.

The Core Pattern

Every wall reset follows the same three-step sequence:

1

Drive Toward the Wall

Move the robot toward a known wall surface — slowly, so you don't slam into it. Use a slow chassis speed (20–30%).

2

Stop at the Target Distance

Loop until the distance sensor reads your target value (e.g. 150mm). Stop the chassis. The robot is now at a known position.

3

Reset Odometry Coordinates

Tell EZ Template's odometry what X or Y the robot is now at. Everything downstream in your route now has a corrected starting point.

Where to Place Resets in a Route

Start of Auton

Most common. Drive to the nearest wall before the route begins. Corrects placement error before any movement accumulates.

Mid-Route Checkpoint

After scoring the first element, reset against a wall before the second phase. Prevents drift from compounding across the full route.

📐
Which wall to use: Use the wall closest to your robot's travel path. The side wall is most common. Make sure the sensor faces the wall squarely — even 10° of angle introduces error.

What the Sensor Actually Measures

The V5 distance sensor fires a Class 1 laser pulse and measures time-of-flight. It returns a value in millimeters. At competition distances (100–800mm from wall), it's accurate to ±5mm consistently — more than precise enough for wall correction.

⚙ STEM Highlight
Physics: Time-of-Flight Measurement
The V5 distance sensor uses LiDAR (Light Detection and Ranging) — the same principle used in self-driving car sensors and surveying equipment. A laser pulse travels at the speed of light (~300,000 km/s). By measuring how long the reflected pulse takes to return, the sensor calculates distance using d = (c × t) / 2, where c is the speed of light and t is round-trip time. At 300mm, the round-trip time is about 2 nanoseconds — which the sensor resolves to ±5mm accuracy.
🎤 Interview line: "We use the V5 distance sensor's LiDAR measurement to perform wall corrections during autonomous. By driving to a known wall surface and reading the exact distance, we reset our odometry coordinates and eliminate accumulated positioning error — the same technique used in industrial navigation systems."
Mounting the Sensor
Where you mount the sensor matters more than how you code it.
⚠️
Most important rule: The sensor face must be parallel to the wall it's measuring. Even a 10° angle causes the reading to be off by ~1.5% — that's 4mm at 300mm range. Small but compounding over multiple resets.

Placement Rules

Face Must Be Unobstructed

No metal, rubber, or wires in front of the laser window. The sensor needs a clear line of sight to the wall — check from all directions, not just front-on.

Mount on a Rigid Structure

Don't mount on a moving arm or intake. Vibration and mechanism movement will cause reading fluctuations. Mount directly to the chassis or a fixed C-channel.

Measure the Offset

The sensor reads distance from its face to the wall. Your robot's edge is further back. Measure the distance from the sensor face to the robot's outer edge — you'll need this offset in your code.

Keep It Low

Mount the sensor as low as practical. The field perimeter wall is 3.5 inches tall. At mid-robot height, the sensor may read the wall cap or an opponent robot instead.

Recommended Positions

Side-Facing (Most Common)

Mounted on the left or right side of the chassis, perpendicular to the drive direction. Used for resetting X coordinate against the side wall.

Front-Facing

Mounted at the front, facing forward. Used for resetting Y coordinate against the back or front wall. Can also detect game elements in the path.

📐
Verify alignment: With the robot against the wall, the sensor should read within ±10mm of your expected value. If it reads further than expected, the sensor is angled or there's an obstruction.
🔬 Check for Understanding
Your distance sensor reads 340mm when the robot is touching the wall. You expected 300mm. What is the most likely cause?
A. The sensor is broken and needs replacement.
B. The battery is low, affecting sensor accuracy.
C. The sensor face is angled or there is an obstruction — it is not reading the flat wall surface.
D. The field perimeter wall is thicker than standard.
EZ Template Code
Declare the sensor, write the wall reset function, reset odometry coordinates.

1. Declare the Sensor

In your globals.cpp or at the top of main.cpp:

// Distance sensor on Smart Port 10
pros::Distance side_dist(10);   // Side-facing, for X correction
pros::Distance front_dist(11);  // Front-facing, for Y correction (optional)

2. Wall Reset Function

Write a reusable function that drives to the wall and stops at a target distance:

// Drive toward the right wall until 200mm from it, then stop
void reset_to_right_wall(int target_mm = 200) {
  chassis.drive_speed(-30);   // Negative = strafe right (holonomic) or adjust for your drive
  while (side_dist.get() > target_mm) {
    pros::delay(10);          // Poll every 10ms
  }
  chassis.drive_speed(0);
  pros::delay(100);           // Settle time before reading

  // Reset odometry X coordinate
  // If robot edge to wall is 200mm, robot center X = 200mm + half_robot_width
  double corrected_x = target_mm + 9.0; // 9 inches = half of 18" robot
  chassis.odom_set_pose({corrected_x / 25.4, chassis.odom_pose_get().y,
                          chassis.odom_pose_get().theta});
}
📏
Units: EZ Template odometry uses inches for position. The distance sensor returns millimeters. Divide mm by 25.4 to convert. The example above handles this conversion.

3. Simpler Pattern — Stop and Check

If you just want to stop at the wall without odometry reset:

// Drive forward until 150mm from front wall
chassis.set_max_speed(25);
chassis.drive_distance(48);    // Drive up to 48 inches

// Override — stop early if sensor triggers
while (!chassis.drive_settled()) {
  if (front_dist.get() < 150) {
    chassis.drive_speed(0);
    break;
  }
  pros::delay(10);
}
chassis.set_max_speed(127);    // Restore speed

4. Mid-Route Reset Pattern

Use this between scoring actions to correct drift mid-route:

void auton_route() {
  // Phase 1 — score first element
  chassis.drive_distance(24);
  chassis.turn_angle(90);
  // ... scoring code ...

  // Wall reset checkpoint — correct X before phase 2
  reset_to_right_wall(200);

  // Phase 2 — now navigating from corrected position
  chassis.drive_distance(36);
  chassis.turn_angle(-45);
  // ... scoring code ...
}
Sensor noise tip: Take 3–5 readings and average them before resetting odometry. A single noisy reading can throw your coordinates off more than drift would have.
// Averaged reading for more stable reset
int avg_distance() {
  int total = 0;
  for (int i = 0; i < 5; i++) {
    total += side_dist.get();
    pros::delay(10);
  }
  return total / 5;
}
Full Routine Example
A complete autonomous with wall resets at start and mid-route.

This example shows a Push Back-style auton that uses two wall resets — one at the start and one mid-route. Adapt the distances and actions to your actual robot and route.

// In globals.cpp
pros::Distance side_dist(10);

// Utility: averaged distance reading
int read_dist_avg(pros::Distance& sensor, int samples = 5) {
  int total = 0;
  for (int i = 0; i < samples; i++) {
    total += sensor.get();
    pros::delay(10);
  }
  return total / samples;
}

// Wall reset utility
void reset_x_from_right_wall(double target_mm = 200) {
  // Slowly strafe toward wall
  chassis.set_max_speed(25);
  chassis.strafe_distance(-12);  // Move right up to 12 inches

  while (!chassis.drive_settled()) {
    if (side_dist.get() < (int)target_mm) {
      chassis.drive_speed(0);
      break;
    }
    pros::delay(10);
  }
  pros::delay(150);  // Settle

  // Average the reading for accuracy
  int actual_mm = read_dist_avg(side_dist);

  // Convert mm to inches, add half robot width (9 in for 18" robot)
  double robot_center_x = (actual_mm / 25.4) + 9.0;

  // Reset odometry X only — keep Y and heading
  auto pose = chassis.odom_pose_get();
  chassis.odom_set_pose({robot_center_x, pose.y, pose.theta});

  chassis.set_max_speed(127);  // Restore
}

// ── Main Autonomous ──────────────────────────────────────────────
void autonomous() {
  // === RESET 1: Correct starting position ========================
  reset_x_from_right_wall(200);

  // === PHASE 1: Score first goal ================================
  chassis.drive_distance(24);        // Drive forward 24 in
  chassis.turn_angle(45);            // Turn toward goal
  chassis.drive_distance(12);        // Approach goal
  // ... scoring action ...
  chassis.drive_distance(-12);       // Back up

  // === RESET 2: Mid-route correction ============================
  chassis.turn_angle(-45);           // Face the wall
  reset_x_from_right_wall(200);      // Re-correct X

  // === PHASE 2: Score second goal ===============================
  chassis.turn_angle(90);            // Face second goal
  chassis.drive_distance(36);
  // ... scoring action ...
}
⚠️
Test this at practice speed first. Run at 25% speed with the terminal open to see what the sensor actually reads. Confirm your target_mm value matches the real robot-to-wall distance before competition.

Debugging Checklist

1

Print sensor values to terminal

Add printf("dist: %d\n", side_dist.get()); inside your loop to see what's happening in real time.

2

Confirm sensor port

Use the Brain screen device info to verify the sensor is connected and returning non-zero values before running auton.

3

Check settle time

If the robot jitters at the wall, increase the pros::delay(150) settle time. The robot needs to stop fully before reading.

4

Verify offset math

Physically measure sensor face to robot outer edge. That measurement must match the offset you add in the odometry reset calculation.

STEM + Interview
The engineering discipline behind wall resets, and how to talk about it with judges.
⚙ STEM Highlight
Engineering: Sensor Fusion & Dead Reckoning Correction
Autonomous navigation without external correction is called dead reckoning — estimating position from a known start point using movement data (encoders, IMU). Dead reckoning error accumulates over time because every small measurement error compounds. This is why submarines surface periodically for GPS fixes, and why aircraft use ILS (Instrument Landing System) to correct approach paths at touchdown.

Wall reset is sensor fusion — combining the distance sensor's absolute positional reference with the odometry system's continuous tracking. The distance sensor acts as a "GPS fix" against a known landmark (the field wall). By periodically injecting this absolute measurement, you break the error accumulation cycle and reset the dead reckoning baseline.
🎤 Interview line: "Our autonomous uses dead reckoning with periodic wall corrections — the same principle aircraft use with ILS approaches. The distance sensor gives us an absolute position reference against the field perimeter, which we inject into our odometry system to break the error accumulation cycle. This made our auton reliable at 95%+ across all battery states."
⚙ STEM Highlight
Math: Error Propagation in Sequential Movements
In a sequential autonomous (move A → move B → move C), position error compounds. If each move has ±1cm of error, after 5 moves you can accumulate up to ±5cm of total error — enough to miss a goal entirely. This is error propagation: the mathematical phenomenon where independent errors in a sequence add rather than cancel. Wall resets interrupt the chain by resetting the accumulated error to near-zero at each checkpoint.
🎤 Interview line: "We analyzed our auton accuracy data and found error was compounding across sequential movements — a classic error propagation problem. Adding wall resets at two checkpoints reduced our end-position error from ±8cm to ±1.5cm. We documented this as part of our testing and iteration process."

Role Connections

🧰 Engineer

You own the implementation: sensor declaration, wall reset function, odometry integration, debugging. Document your sensor placement decision and offset calculation in the notebook.

📊 Strategist

Wall resets take time — typically 1–2 seconds each. During route planning, decide whether the accuracy gain justifies the time cost for your specific route. That's an expected value decision.

🏎 Driver

You need to place the robot consistently so the first reset works correctly. Practice placing the robot in the same spot within ±1cm — the reset corrects most of it but extreme placement errors may exceed the sensor's reach distance.

📝 Notebook

Document: sensor port and placement diagram, offset measurement, target distances, before/after accuracy data. Judges want to see the design decision — why you chose wall correction over pure odometry.

Judge Interview Questions

Q

"How reliable is your autonomous?"

"Before adding wall resets, we were at about 70% reliability due to battery and placement variation. After implementing distance sensor corrections at the start and one mid-route checkpoint, we're consistently above 95% in practice — and we have data to back that up in the notebook."

Q

"What sensors does your robot use?"

"We use an IMU for heading, rotation sensors for odometry tracking wheels, and a V5 distance sensor for wall position correction. The distance sensor is the key to consistent autonomous — it gives us an absolute reference point that resets accumulated encoder drift."

Q

"How did you test this?"

"We ran 20 trials each — with and without wall resets — measuring end-position error against a target marker. The data is in our notebook. Without resets, average error was 8cm. With two resets, it dropped to under 2cm. That data justified adding the extra 2 seconds to our route."

🔬 Check for Understanding
A judge asks: "Your wall reset takes 1.5 seconds — was it worth it?" What is the best response?
A. "Yes, it makes the robot look more advanced."
B. "We have data showing end-position error dropped from 8cm to under 2cm. At our target goal distance, that 6cm improvement is the difference between scoring and missing — so the 1.5 seconds is worth it."
C. "All top teams use distance sensors so we added it too."
D. "It was our coach's idea."
← ALL GUIDES