Skip to the content
2 layers87.2 × 93.9 mmWRO RevA, the printed circuit board in 3D

CETYS Mexicali WRO2026 FoxRobotics Team

Size
87.2 × 93.9 mm
Copper layers
2
Thickness
1.6 mm
Parts
26
Nets
57
Pads
133
Tracks, vias
279, 46
Pours
2
Routed
Yes
KiCad
KiCad 9.0 (file 20241229)
Created
13 Apr 2026
Updated
7 Nov 2026

Overview

WRO RevA is an open-source printed circuit board by Nakashima26, from the Nakashima26/WRO_FE_2026_FoxRobotics repository on GitHub, published under the MIT licence. It is a 2-layer board of 87.2 × 93.9 mm with 26 parts on 57 nets, routed with 279 tracks and 46 vias.

It is built around the BOB-12009 and ROB-14450. Its parts include 4 capacitors, 4 ICs, 3 connectors, 2 resistors and 2 switches. It belongs with the ESP32 boards of this library.

Main components

2

README

README.md

WRO 2026 — Future Engineers | Self-Driving Car

Team: FoxRobotics | Members: Erick Blanco · Jesse Banda · César Emiliano Ahumada | Coach: Daniel Millan | Country / Region: México — Baja California | Season: 2026


Table of Contents

  1. Vehicle Overview
  2. Mechanical Design & Mobility
  3. Power Architecture & Sensors
  4. Software Architecture
  5. Systemic Thinking & Engineering Decisions
  6. Testing & Validation
  7. How to Build & Run
  8. Repository Structure
  9. Videos
  10. Photos

Companion document: Engineering Journal — the dated, phase-by-phase build log, from the pre-repo design work through today, tied to commits. §5.3 Iteration log and §6.5 Milestones are the thematic views of the same history.


1. Vehicle Overview

Isometric view of the vehicle

Our vehicle is a custom-built autonomous car for the WRO 2026 Future Engineers — Self-Driving Cars challenge. It completes 3 laps around a randomized track, and in the Obstacle Challenge it also detects and correctly passes coloured traffic-sign pillars (red → keep the pillar on the car's left / pass on its right; green → keep it on the right / pass on its left) before parking at the end.

The car uses two controllers working together: a Raspberry Pi runs the camera vision pipeline (a Raspberry Pi 4 at the national final, a Raspberry Pi 5 for the international final) and the high-level path planner (Pure Pursuit), and an ESP32 runs the real-time control loop, the state machine and all the actuators. They talk over a UART link with a small line-based protocol ("V2"). This split is the central architectural decision of the project and is explained in Section 4 and Section 5.

Key specifications:

ParameterValue
Dimensionsv1: 210 × 140 × 80 mm body, ≈240 mm overall with the extension added to drive out of the parking lot · v2: ≈170 × 130 × 110 mm (168.7 × 128 mm in CAD; height includes the camera ribbon over the top, §2.6)
Weight564 g
Drive typeRear-wheel drive (RWD)
SteeringAckermann rack-and-pinion, SG90 servo — v2: 53° inner / 37° outer wheel at full lock, ~106% Ackermann (§2.4)
High-level controllerRaspberry Pi 5, 16 GB + Active Cooler (vision + Pure Pursuit) — Raspberry Pi 4 Model B until the national final (§3.4)
Real-time controllerESP32 DevKit (FSM, PID, motor & sensor I/O)
Inter-controller linkUART @ 115200 baud, line protocol "V2" (see §4.2)
VisionRaspberry Pi Camera, NoIR wide-angle lens (FOV ≈ 120°), processed at 640 × 480; custom lens-shading calibration on the Pi 5 (ERR-03)
Distance sensorsHC-SR04 (5V) × 3 — left, right, front — via 5V↔3.3V level shifter · v2: + VL53L1X ToF × 4, in integration (§3.2)
IMUMPU-6050 (gyroscope + accelerometer) · v2: BNO085 with on-chip sensor fusion, in integration (§3.2)
Drive motorv1: N20 DC gear motor (50:1) · v2: Pololu 50:1 12 V gear motor with encoder · + 2:1 stage → 100:1 total
Motor driverTB6612FNG
Battery3S LiPo 11.1 V 2200 mAh
Logic powerMINI560 step-down, 5 V

1.1 Design goals

One reliable vehicle that finishes both challenges — scoring for completing three laps consistently over completing them fast. Everything below follows from that.

  • Fixed architecture from day one: Raspberry Pi 4 + ESP32. The Pi does all image processing and vision; the ESP32 does all peripheral I/O — both sensing and actuation. This split was decided before the first line of code and never revisited.
  • Small footprint for maneuverability. Comfortably inside the rulebook envelope with ~10 cm of margin on width and length — the car is ≈ 20 × 10 cm, deliberately smaller than the limit so it has room to maneuver in the obstacle field.
  • Mechanically extensible. The chassis and the PCB were designed so components could be added later without a redesign. This paid off directly: the front ultrasonic — added for the obstacle-round segmented turn (see §4.5) — went from idea to mounted-and-wired in under 30 minutes because both the chassis and the PCB already had the space and a spare header.
  • Tight-turn capable. Rack-and-pinion steering driving both wheels symmetrically (§2.4) so the car can take the obstacle-round corners without a multi-point turn.
  • Room for a printed differential so the rear wheels can turn at different speeds through a corner without scrub.
  • Electronics-first packaging. The chassis was sized around the electronics — the Raspberry Pi 4 above all — and the PCB was then laid out to fit the finished mechanical model, not the other way around.

1.2 Bill of Materials

Custom Manufactured Parts

IDComponentDescriptionQuantitySupplierApproximate Cost
1BaseChasisMain body of the vehicle.1Custom made, 3D printed1.6 USD
2TopShellUpper part of the vehicle.1Custom made, 3D printed1 USD
3CremalleraRack used for steering.1Custom made, 3D printed0.1 USD
4ServoGearDirectionPinion for the steering system, directly connected to the servo.1Custom made, 3D printed0.5 USD
5LinkageDirectionLinkage between the rack and steering knuckle.2Custom made, 3D printed0.05 USD
6SteeringKnuckleAllows lateral wheel movement for steering.2Custom made, 3D printed0.15 USD
7DCsupportHolds the DC motor in place.1Custom made, 3D printed0.05 USD
8RingDifferentialMain driven gear of the differential that transfers power to the axle assembly.1Custom made, 3D printed0.25 USD
9PlanetDifferentialAllows torque distribution between both wheels while enabling different wheel speeds during turns.2Custom made, 3D printed0.1 USD
10PinionDifferentialTransfers rotational motion from the motor to the differential gear system.1Custom made, 3D printed0.1 USD
11SunDifferentialTransfers torque from the differential gears to the wheel axle.2Custom made, 3D printed0.1 USD
12CameraBaseHolds the camera frame in place.1Custom made, 3D printed0.1 USD
13CameraBackRear section of the camera frame. Connects to the CameraBase.1Custom made, 3D printed0.1 USD
14CameraFrontCamera frame.1Custom made, 3D printed0.2 USD
15UltrasonicSupportHolds an ultrasonic sensor in place (used for the left, right and front sensors).3Custom made, 3D printed0.3 USD

LEGO Components

IDComponentDescriptionQuantitySupplierApproximate Cost
16Lego 6135494Front wheel axle.2LEGO0.8 USD
17Lego 4535768Rear wheel axle.2LEGO1 USD
18Lego 6121485Reduces friction on the rear wheels.2LEGO0.4 USD
19Lego 4299389Rim for rear wheels.2LEGO1.2 USD
20Lego 4184286Tires for rear wheels.2LEGO3.5 USD
21Lego 6251174Rim for front wheels.2LEGO1.2 USD
22Lego 6182551Tires for front wheels.2LEGO3.82 USD

Electronics

IDComponentDescriptionQuantitySupplierApproximate Cost
23ESP32Real-time controller: sensor I/O, cascade PID, finite state machine, actuator PWM.1Unit Electronics8 USD
24Raspberry Pi 5 (16 GB) + Active Cooler + M.2 HAT+High-level controller: computer vision and Pure Pursuit path planning. Replaced the Raspberry Pi 4 (60 USD) after the national final; price includes taxes and shipping.1Official reseller410 USD
25Mini560 5VStep-down regulators. v2 uses two: one only for the Raspberry Pi 5, one for the ESP32, servo and sensors (v1 had one for everything).2Amazon12 USD
26BNO0859-axis IMU with on-chip sensor fusion (heading at 100 Hz). Replaced the MPU-6050 (3 USD) in v2.1Local purchase27 USD (500 MXN)
38VL53L1XLaser time-of-flight distance sensors — front, left, right and rear (v2).4Local purchase27 USD total (500 MXN)
27HC-SR04Ultrasonic distance sensors — left, right (wall following) and front (obstacle-round cornering).3Unit Electronics10.5 USD
28Level ShifterLogic-level converter for the 5 V HC-SR04 echo lines into the 3.3 V ESP32.1Unit Electronics7 USD
29Driver TB6612FNGMotor driver controlling speed and direction of the DC drive motor.1Unit Electronics5 USD
30RaspiCamera V2Camera module used for computer vision. Came with both ribbon cables: 15-pin for the Raspberry Pi 4 and 22-to-15-pin for the Raspberry Pi 5.1Amazon10 USD
31Custom PCBPower distribution and all signal connections. v1: single board (5 USD); v2: two-floor board, in design — price pending.1JLCPCB5 USD (v1)

Power System

IDComponentDescriptionQuantitySupplierApproximate Cost
32Ovonic 2200mAh 3S3-cell LiPo battery powering the robot's electronics and drive system.1E-Bay13 USD

Actuators

IDComponentDescriptionQuantitySupplierApproximate Cost
33Pololu 50:1 12 V gear motor with encoderDrive motor; the encoder measures speed and distance. Replaced the N20 50:1 (6 USD) in v2.1Pololu20 USD
34SG90 ServoMicro servo motor used for steering control.1Unit Electronics6 USD

Fasteners

IDComponentDescriptionQuantitySupplierApproximate Cost
35M3 ScrewsUsed for structural assembly and component mounting.23Local Hardware Store1 USD
36M3 NutsUsed to secure structural and electronic components.1Local Hardware Store0.05 USD
37M2 NutsUsed to secure servo motor and servo pinion3Local Hardware Store0.15 USD

Total Estimated Cost

VersionTotal
v1 — national final~155 USD
v2 — international final~576 USD + v2 PCB (pending)

Where the increase comes from: +410 USD Raspberry Pi 5 bundle, +27 BNO085, +27 VL53L1X ×4, +20 encoder motor, +6 second regulator; −69 USD for the parts that left the car (Raspberry Pi 4, MPU-6050, N20). About 85% of the increase is the Raspberry Pi 5, justified by the profiling in §3.4: 40 fps vs ~15 fps, no thermal throttling.

1.3 What changed for the international final (v2)

After winning the national final (2026-09-19, release v1.0-nacional) we reworked the parts of the car that were limiting it. Each change has its own section with the numbers behind it.

Areav1 (national final)v2WhyDetails
Steering geometryAnti-Ackermann: the outer wheel steered more than the inner one (39.5° inner / 42.8° outer)Ackermann corrected: rack joints 43 → 47 mm apart, tie rods 18.13 mmBoth front wheels now roll around the same turning center instead of fighting each other2.4
Steering pinionModule 1, 14 teethModule 1, 19 teeth; servo moved 2.5 mm away from the rackSame servo travel moves the rack 36% further: ~37° → 53° on the inner wheel (measured in CAD)2.4
Main computerRaspberry Pi 4Raspberry Pi 5, 16 GB + Active CoolerThe Pi 4 was compute-bound at 14–18 fps and hit thermal throttling at 84 °C; the Pi 5 runs the same pipeline at ~40 fps at 52 °C3.4
Chassis layout≈24 cm long; Raspberry Pi enclosed in the center; motor perpendicular to the rear axle (bevel gears)≈17 cm long; battery in the center where the Pi was; Pi 5 on top, open to the air; motor parallel to the axle (spur gears, same 2:1)Tighter turns and more room to dodge and park; the enclosed Pi overheated (84 °C, throttling)2.6
Distance sensing3 × HC-SR04 only3 × HC-SR04 + 4 × VL53L1X ToF (front, left, right, rear), cross-checked against each otherEach sensor type fails differently against the black walls: the ultrasonic gives phantom echoes, the ToF can lose a dark wall. Using both lets each one veto the other's known failure3.2
Drive motorN20 50:1, open-loopPololu 50:1 with encoder (mounted; speed loop pending)Maneuvers changed with battery voltage; the encoder gives measured speed and distance2.6
IMUMPU-6050, gyro rate integrated on the ESP32BNO085, fused heading computed on the sensor (UART-RVC, 100 Hz)Integrated heading was 6.5% low over a run and carried a −7.5° bias after every corner maneuver3.2
PowerOne 5 V regulator for everythingTwo regulators: one only for the Raspberry Pi 5Servo current spikes must not sag the Pi's supply; the Pi 5 draws more3.1
PCBOne boardTwo-floor board: power floor + logic floor (in design)The shorter chassis has less area, and four ToF + BNO085 need new connectors3.3
Camera colorFixed white-balance gains only (Pi 4)Lens-shading table calibrated for our lens + gains, as a project tuning fileThe new image processor of the Pi 5 showed a magenta ring at the frame edges, close to the pink parking walls and red pillarsERR-03
DocumentationOne README+ releases, test record, engineering log (ERR-10 onward)One release per event; every failure tied to a run number and a commit§6

2. Mechanical Design & Mobility

2.1 Chassis selection

The chassis was designed from scratch to fit all the components we needed for competition. We printed it in red and black SUNLU PLA on a Bambu Lab A1, keeping the structure as light as possible without sacrificing the rigidity the drivetrain and electronics require.

For wheel transmission shafts, we used LEGO axles throughout: part 6135494 for the front and part 4535768 for the rear. This wasn't an aesthetic choice — LEGO axles have much better dimensional consistency than fully printed shafts, which flex under load and cause alignment issues. We also added LEGO bushings (6121485) to the rear axle to cut down on friction between moving parts.

ComponentMaterial / PartPurpose
ChassisSUNLU PLAMain robot structure
Front AxlesLEGO 6135494Power transmission
Rear AxlesLEGO 4535768Rear drivetrain support
BushingsLEGO 6121485Friction reduction
PrinterBambu Lab A1Manufacturing process

We used PLA because it prints fast, doesn't warp like ABS, and is stiff enough for indoor competition conditions. PETG has better impact resistance and ABS handles heat better, but neither of those properties matters much for a robot running on a flat mat indoors. What did matter was being able to iterate quickly and get consistent parts, and PLA delivered on both.

2.2 Wheels

We tested several wheel options before settling on LEGO parts. The rear wheels use rim 4299389 with tire 4184286, and the front uses rim 6251174 with tire 6182551. Both have a 43 mm outer diameter, which keeps the ride height even front to rear.

Since the drivetrain already uses LEGO axles, LEGO-compatible rims were the obvious fit — they mount directly without adapters, which removes a potential source of wobble at the wheel interface.

The 43 mm diameter was also validated against our motor RPM target. At our gear ratio, this diameter puts normal operation in the 40–70% PWM range, which gives us enough resolution for smooth speed control. A noticeably larger wheel would push operating duty cycles above 85% and compress the usable throttle range.

We ran the car at full throttle on the competition mat surface and saw no detectable slip at the rear. The LEGO rubber compound grips the white matte WRO field without any prep needed.

2.3 Drive system (torque vs. speed analysis)

The main drive is an N20 DC motor with a 50:1 internal gearbox — compact at 12 × 10 × 26 mm and still enough torque for a ~1.5 kg vehicle. Between the motor output shaft and the differential, we added a 2:1 LEGO gear stage, bringing the total drivetrain reduction to 100:1 and estimated rear axle torque to about 1.76 kg·cm.

Why 100:1 and not just 50:1?

We ran the 50:1 configuration first. It was faster, but corner exits were inconsistent — the rear wheels would occasionally lose traction under acceleration, causing yaw disturbances the PID couldn't fully catch. At 100:1, top speed dropped but torque delivery became smooth and predictable all the way through the speed range. Corner exits became repeatable, which turned out to be a prerequisite for reliable PID tuning.

The ratio also keeps the motor in its efficient RPM band during most of the run, which matters because the motor shares a power source with the logic rail.

Official time at the national final, Open Challenge round 1: 57.455 s for the three laps, driven at a conservative speed for reliability. v2 spends that headroom with a planned route and a speed profile (§4.9).

The takeaway: we prioritized consistency over raw speed. A robot that reliably finishes 3 laps scores more than one that's faster but unpredictable.

2.4 Steering — rack-and-pinion with Ackermann geometry

Steering is controlled by an SG90 servo connected to both front knuckles through a rack-and-pinion mechanism with symmetric tie rods.

Mechanism specs (v1, national final):

ParameterValue
ServoSG90 (0°–180° range)
Firmware straight-ahead trim80° (servo-horn spline offset; centroServo in firmware)
PinionModule 1, 14 teeth
Pinion pitch diameter14 mm (dp = m × z = 1 × 14)
Pinion outer diameter16 mm (dp + 2×addendum = 14 + 2)
RackModule 1, 11 teeth, 27.5 mm total travel
Rack displacement per servo degree0.1222 mm/°
Transmission ratio2.50° servo : 1° wheel
Geometric wheel steering range±43° from center
Firmware-clamped servo command20°–150° (≈ ±35° usable at the wheel)

Kinematic analysis:

The 14 mm pitch diameter gives a pitch circumference of 43.98 mm. Each degree of servo rotation moves the rack 0.1222 mm. At 90° per side from center, the rack travels 11.00 mm per side — producing ±43° at the front wheels.

The outer diameter of 16 mm confirms the module (d_outer = dp + 2×m = 14 + 2 = 16 mm).

The 2.50:1 ratio reduces steering sensitivity at the wheel, which gives the inner control loop finer resolution at its update rate. A lower ratio would make steering response too abrupt.

The firmware never commands the full mechanical range: escribirServo() is clamped to 20°–150° (about ±35° at the wheel) so a saturated control output can't drive the rack into its physical end stop. That still clears the tightest Open-Challenge corridor (600 mm) and the maneuvering the Obstacle Challenge needs.

Why rack-and-pinion over a direct servo arm?

A direct arm only controls one wheel directly. The opposite knuckle, linked by a fixed-length tie rod, gets an angle that's geometrically correct only at center — producing toe error everywhere else. The rack pushes both tie rods symmetrically, so both wheels get the right angle at every steering position. Combined with the Ackermann geometry of the knuckles, each wheel tracks its own correct turning radius. No lateral scrub, and steering response is linear across the full range.

v2 redesign (October 2026) — Ackermann fix and a bigger pinion

In v2 we redesigned this mechanism because of two problems: the geometry was anti-Ackermann, and the car could not turn tightly enough. We simulated the linkage in Python with the exact CAD dimensions (the model matched the CAD within ~1°) before reprinting anything.

Geometry reference (top view, wheels straight, measured in SolidWorks):

ParameterValue
Kingpin track T (distance between the two knuckle pivots)60 mm
Wheelbase L (front kingpin line → rear axle)112.85 mm
Knuckle steering arm (pivot → tie-rod joint)12.49 mm, pointing ~43° outward and backward
Rack joints behind the kingpin line18.94 mm
Servo swing actually used±71° (measured from the rack travel, not the nominal ±90°)
Problem 1 — anti-Ackermann (fixed)

In a turn, the inner wheel follows a smaller circle than the outer wheel, so it must steer more. Correct (100%) Ackermann is reached when

cot(δ_outer) − cot(δ_inner) = T / L = 0.532

and the axis lines of both front wheels cross on the rear axle line.

In v1 the rack joints were only 28.5 mm apart with 26 mm tie rods. We simulated the linkage in Python with the exact CAD dimensions, and the model matched the CAD within ~1°. At full travel the car steered 39.5° on the inner wheel and 42.8° on the outer wheel: the outer wheel was steering more than the inner one. The two front wheels were trying to turn around different centers, so one of them always dragged sideways. That cost traction and current in every corner, and the car turned wider than the servo command implied.

Because the knuckles had to stay as they were (a new knuckle means a new arm, and the rack position is fixed by the chassis), we only changed the spacing between the rack joints and the tie-rod length. Those two values must change together: for the wheels to point straight with the rack centered, the tie rod must be

linkage = √( (38.66 − spacing/2)² + 9.94² ) (mm, center to center)

Rack joint spacingTie rodAckermann at 30°40°45°50°55°
28.5 (v1)26.0anti-Ackermann
43.0 (intermediate)19.8351%62%69%76%84%
47.0 (v2)18.1376%89%95%102%110%
50.016.8999%111%117%124%131%

(Percentage = how much of the ideal inner/outer difference the linkage achieves. Below 100% the outer wheel steers slightly too much; above 100% it steers too little.)

Why 47 mm: with a fixed knuckle, Ackermann cannot be exact over the whole range, because the percentage grows as the wheels turn. We chose the spacing that is closest to 100% in the 40°–50° range, which is where the car actually turns at corners and during parking. At small angles the error is under 0.7°, so it does not matter there. Each 0.1 mm of tie-rod error toes a wheel by ~0.5°, so the printed linkages are trimmed in 0.05–0.1 mm steps until the wheels are straight.

Problem 2 — turning radius (bigger pinion)

The steering angle depends almost only on how far the rack moves, and with the v1 pinion that was ±8.7 mm: only ~37° on the inner wheel. We looked at three options: shorter knuckle arms, moving the rack, and a bigger pinion. The bigger pinion was the only one that needed no new chassis or knuckles.

v1v2
PinionModule 1, 14 teethModule 1, 19 teeth (20° pressure angle)
Pitch / outer diameter14 / 16 mm19 / 21 mm
Rack travel per servo degree0.122 mm/°0.166 mm/°
Rack travel at ±71° servo±8.7 mm±11.8 mm
Inner / outer wheel at full lock~37° / ~32° (with 43 mm spacing)53.1° / 37.0° (measured in the CAD assembly; the linkage model predicted ~50° / ~37°)
Turning radius at the rear-axle center (L / tan δ_inner + T/2)~208 mm (v1: 147 mm wheelbase, 39.5°)~115 mm (v2: 113 mm wheelbase) — −45%
Ackermann at full lockanti-Ackermann~106% (ideal outer for 53.1° inner = 37.9°, measured 37.0°)
  • Servo position. The pitch radius grows from 7 to 9.5 mm, so the servo axis moved 2.5 mm away from the rack with a spacer on its mount. The rack and the tie-rod joints stay at the same height, so the linkage geometry above is not affected.
  • Pinion profile. We generated the involute tooth profile with our own script (Mecanica/Engranes/gen_pinon.py) and exported it as a single closed DXF contour that we extrude in SolidWorks. It includes 0.10 mm of backlash for 3D printing.
  • Toggle limit. The linkage would lock (arm and tie rod aligned) at around 16 mm of rack travel. If the servo ever reached a true ±90°, the 19-tooth pinion could push the rack to ±14.9 mm. The intended mechanical stop is the knuckle touching the chassis before that point, and the servo output is also clamped in software.
  • Servo load. The bigger pinion needs ~1.36× more servo torque for the same rack force. It also loses some angular resolution, which is still fine for an SG90 in a 0.5 kg car. The servo must not be left stalled against the stop, because it heats up and drags down the 5 V rail.

Servo calibration. The servo-to-wheel relation is no longer linear: near full lock the wheels turn faster per servo degree. The servo map and the steering gains in the ESP32 firmware are recalibrated on the assembled car (pending).

2.5 Custom parts & assembly

Every structural part is 3D-printed in SUNLU PLA on a Bambu Lab A1. The mechanical model was built first; the PCB was then laid out to fit it. Editable SolidWorks parts are in models/CAD/, printable meshes in models/STL/, isometric renders in models/renders/.

Full vehicle CAD assembly

RenderPartFunction / design note
BaseChasis renderBaseChasisMain structure. Sized around the electronics (Raspberry Pi 4 first); carries the PCB, steering, drivetrain and every sensor mount.
TopShell renderTopShellTop cover — closes the electronics bay and protects the wiring.
ServoGearDirection renderServoGearDirectionPinion pressed onto the SG90 output shaft — module 1, 14 teeth (19 teeth in v2, §2.4; profile generated by Mecanica/Engranes/gen_pinon.py).
Cremallera renderCremallera (rack)Module 1, 11 teeth, 27.5 mm travel. Converts servo rotation into lateral travel for the tie rods.
LinkageDirection renderLinkageDirection ×2Tie rods from the rack ends to the steering knuckles — symmetric, so both wheels get the correct angle at every rack position.
SteeringKnuckle renderSteeringKnuckle ×2Front-wheel pivots; their geometry sets the Ackermann steering angles.
Differential renderDifferential (Ring / Planet ×2 / Pinion / Sun)Printed open differential — lets the rear wheels turn at different speeds through a corner.
DCsupport renderDCsupportMounts the N20 gear motor to the chassis.
UltrasonicSupport renderUltrasonicSupport ×3Two identical side mounts; one slightly smaller front mount, added later for the obstacle-round segmented turn.
Camera cage renderCameraHoldStructure in charge of holding the camera. Sets the fixed ~20° downward tilt the BEV homography is calibrated against (§3.2).
Assembly order
  1. Chassis base — the reference part everything mounts to.
  2. Steering — press the pinion onto the servo and seat the servo in the chassis; slide in the rack; link each rack end to a SteeringKnuckle with a LinkageDirection tie rod; fit the knuckles and the front LEGO axles.
  3. Drivetrain — N20 motor into the DCsupport; assemble the printed differential; rear LEGO axles with bushings.
  4. Sensor mounts — the two side UltrasonicSupports (identical) and the smaller front one; the camera cage (base + back + front) with the camera.
  5. Electronics — PCB onto the chassis bosses; wire the Pi 4, ESP32, the three HC-SR04 (through the level shifter), the MPU-6050, the TB6612 + motor, the servo, and the start button + status LED.
  6. TopShell — close the bay.

All fasteners are M3 (M2 nuts on the servo horn and pinion).

2.6 v2 chassis — shorter car, Pi on top

Status: designed in SolidWorks, being printed. Final dimensions and weight will be measured on the printed car.

For the international final we rebuilt the chassis around two problems we kept seeing at the national final:

  1. The car was long for the obstacle field. The body was 210 mm, but it reached ≈24 cm overall with an extension we added so the car could drive out of the parking lot comfortably. At that length every dodge swept a lot of floor, and the parking maneuver had little room in the lot.
  2. The Raspberry Pi overheated. It sat enclosed in the middle of the chassis. With the remote-view client running it reached 84 °C and throttled its CPU (ERR-27), which lowered the vision frame rate.

What we changed

ChangeHowWhy
Motor parallel to the rear axleThe drive motor now lies along the axle and drives the differential through spur gears (module 1, 15-tooth pinion on the motor's D-shaft, 30-tooth ring on the differential) instead of the perpendicular bevel pairA motor perpendicular to the axle adds its whole length to the car. Lying along the axle, it adds almost nothing.
Battery in the centerThe 3S pack sits crosswise in a side-loading tunnel, in the space the Raspberry Pi used to takeThe heaviest part ends up in the middle and low, which balances the load front to rear. The side tunnel makes battery swaps quick.
Raspberry Pi 5 on topThe Pi moves from the enclosed center bay to the top of the carThe Active Cooler needs free air. Enclosed, the Pi recirculated its own hot air. On top, it also stays reachable for the camera cable and the SSD.
Encoder motorPololu 50:1 12 V gear motor with a quadrature encoder replaces the plain N20; same 50:1 ratioMotor speed is open-loop today, so maneuvers change with battery voltage (ERR-11). The encoder lets the ESP32 hold a speed and measure distance, as the rules' reference build suggests. Mounted; firmware integration pending.
Overall length ≈24 cm → ≈17 cm (width 128 mm)Result of the changes aboveSee below

Why a shorter car turns tighter. For Ackermann steering, the radius of the path at the center of the rear axle is

R = L / tan(δ_inner) + T/2

where L is the wheelbase and T the kingpin track (60 mm). Shortening L shrinks R directly, at the same steering angle. With the v2 steering (53° inner wheel, §2.4) and the v2 wheelbase of ≈113 mm (CAD), R ≈ 115 mm. The v1 car had a wheelbase of ≈147 mm (measured) and ~40° of steering, so R ≈ 208 mm. The turning radius is therefore ≈45% smaller: about half from the shorter wheelbase, about half from the bigger steering angle. A smaller radius means a dodge needs less lateral room, the stop-and-turn corner maneuver needs less space ahead of the front wall, and the car fits the parking lot with more margin.

The drivetrain keeps its ratio. The old bevel pair was 36:18 = 2:1, and the new spur pair is 30:15 = 2:1. The total reduction stays at 100:1, so the torque and speed analysis of §2.3 still holds. Spur gears are also easier to print accurately and to align than bevel gears. We checked the tooth strength with the Lewis bending equation (8 mm face, at the N20's stall torque): ≈5.7 MPa, roughly 9× below the strength of printed PLA. It is re-checked with the stall torque of the encoder motor. The gear center distance is designed at 22.6–22.7 mm (22.5 mm nominal) to leave printing clearance. The involute profiles are generated by our own script and exported as DXF; SolidWorks Standard has no gear generator.

What stayed about the same, on purpose: the height of the chassis, for stability in fast turns (the v2 car is ≈110 mm tall, but only the camera ribbon over the top reaches that); the LEGO axles and wheels (§2.1, §2.2); and the camera height and angle, so the bird's-eye-view calibration concept carries over (it is re-calibrated on the new mount).


3. Power Architecture & Sensors

3.1 Power budget

The whole vehicle runs off an Ovonic 2200mAh 3S LiPo. Power splits two ways: the motor driver takes battery voltage directly for the DC motor, and everything else goes through a MINI560 step-down converter producing a stable 5V at up to 5A.

RailSourceConsumersMax Current Draw
5V LogicMINI560 Step-Down ConverterRaspberry Pi 4 + RaspiCam V2, ESP32, HC-SR04 ×3, MPU6050, SG90~4.0 A
Battery / Main PowerOvonic 2200mAh 3S LiPoEntire vehicle power distribution~35 A discharge capability
Motor PowerMotor Driver directly from 3S LiPoDC drive motor~1.6 A peak
3.3V InternalESP32 internal regulatorI²C communication and internal ESP32 logic, Level Shifter~200 mA

The Ovonic battery is rated 120C continuous, which is theoretically 264 A. We're drawing about 4.5 A peak — under 2% of its discharge capability. There's no shortage of headroom here.

The Raspberry Pi and the ESP32 share the 5 V rail but the DC motor is fed straight from the battery through the TB6612FNG, so stall-current spikes on the motor never sag the logic supply.

v2 power budget

Design values from the component datasheets and the Raspberry Pi documentation. Each rail will be measured with an inline meter on the assembled v2 car, and the measured values will replace these.

The Raspberry Pi 5 draws more than the Pi 4 and is sensitive to voltage drops: when its supply sags it throttles the CPU, which directly lowers the vision frame rate. We already saw this on the Pi 4 when it was fed through Dupont jumpers (throttled=0x50005, CPU down to 600 MHz, ERR-08). v2 therefore has two 5 V regulators: one only for the Raspberry Pi 5, and one for everything else. The servo's current spikes can no longer pull down the Pi's supply.

RailLoadTypicalDesign peakBasis
5 V-A (Mini560 #1, 5 A)Raspberry Pi 5 under vision load1.5 A2.5 A0.8 A bare-board active (Raspberry Pi docs) + 4 cores busy; peak covers load spikes
Camera v20.25 A0.25 ACamera module figure
Active Cooler fan0.05 A0.1 AFan at full speed above 75 °C
Rail total1.8 A2.85 A57% of the regulator's 5 A at peak
5 V-B (Mini560 #2, 5 A)ESP32 (radio off)0.08 A0.25 ADatasheet
SG90 servo0.25 A0.70 ARunning current; peak = stall
HC-SR04 × 30.045 A0.045 A15 mA each
VL53L1X × 40.08 A0.16 A~20 mA each ranging, 40 mA peak
BNO0850.013 A0.013 ADatasheet operating figure
Rail total0.47 A1.17 A23% of the regulator at peak
Battery 11.1 VDrive motor via TB6612—1.6 APeak measured on v1 (N20); to be re-measured with the encoder motor
5 V-BMotor encoder0.01 A0.01 AHall-effect encoder

Battery current. With ~90% regulator efficiency, the two 5 V rails at design peak draw 5 V × (2.85 + 1.17) A / 0.9 ≈ 22 W, which is ≈2.0 A from the 11.1 V pack. Adding the motor's 1.6 A gives ≈3.6 A worst case. The 2200 mAh pack would last over 35 minutes even at that worst case, against a 3-minute round, so capacity is not the constraint. Voltage is. A freshly charged pack makes the motor ~17% stronger in low-PWM maneuvers (ERR-11), so we race inside an 11.70–12.15 V window.

Heat. At its typical 1.8 A, regulator #1 loses about 1 W at 90% efficiency. It is mounted in the airflow of the Pi on top of the car.

Check before every session: vcgencmd get_throttled must read 0x0 under full vision load.

3.2 Sensor selection and placement

SensorPurposePlacementNotes
Raspberry Pi Camera Module V2Lane, corner-line and pillar detectionFront-center, ~20° downward tiltMain vision system, OpenCV on the Pi
HC-SR04 (left)Left wall distanceLeft side of the chassisFeeds the wall-centering PID
HC-SR04 (right)Right wall distanceRight side of the chassisFeeds the wall-centering PID
HC-SR04 (front)Distance to the wall ahead when approaching a cornerFront bumper, facing forwardObstacle round only — triggers the CRUCERO → MANIOBRA sequence
MPU-6050 (v1)Heading integration during cornering and recoveryCenter of chassisGyro Z integrated into anguloGyro, echoed back to the Pi
BNO085 (v2, in integration)Fused heading at 100 HzCenter of chassis, near the rotation axisReplaces the MPU-6050; heading computed on the sensor
VL53L1X ToF ×4 (v2, in integration)Near-field distance (≤ ~80 cm) with a software-set field of viewFront, left, right and rear, ~50 mm highCross-checked against the HC-SR04 — see Why both
Camera system

The camera handles lane geometry (via a bird's-eye-view transform), the orange corner-line markers, and red/green pillar detection. Image processing runs on the Raspberry Pi (Pi 4 → Pi 5 in v2) with OpenCV in real time and drives the Pure Pursuit planner.

It is mounted front-center with a ~20° downward tilt. We tested a horizontal mount first, but that captured too much background, which slowed detection and added noise. Tilting it down focuses the field of view on the track and the obstacle zone, which cut both false positives and computational load. The exact tilt is baked into the bird's-eye-view homography during calibration (see §4.3), so the mount must not move after calibration.

The lens is a wide-angle NoIR unit (~120° FOV), chosen over the original ~63° lens so the camera sees far enough ahead to react to a pillar and read the corner on the same frame. The wide lens ships without an IR-cut filter, which gave the raw image a heavy red cast and broke every HSV mask. The libcamera capture pipeline pins white-balance instead of letting it float — libcamerasrc awb-enable=false colour-gains=<1.2,1.5> — so the correction holds across venue lighting, and the pillar HSV ranges were re-tuned on the corrected image (see ERR-03).

v2 (Raspberry Pi 5): fixed gains alone are not enough. The lens also needs its own lens-shading table (ALSC), otherwise the edges of the frame turn magenta. We calibrate that table from photos of a white sheet with the official Raspberry Pi tuning tool and ship it as a project tuning file, src/RASPI/cam/camera_tuning/. Result on a white sheet: R/G and B/G = 1.00 at the center and at all four corners (they were 1.3–1.4 at the corners).

HC-SR04 ultrasonic sensors

The left and right sensors drive lateral positioning and wall following. The front sensor was added for the Obstacle Challenge: because that round uses a segmented, stop-and-maneuver turn instead of a continuous arc (see §4.5), the car needs to know how far it is from the wall ahead so it can decide when to stop cruising and which maneuver (forward arc or reverse pivot) to run.

We originally tested VL53L0X time-of-flight sensors. On paper they win — ±3 mm accuracy versus ±15 mm for the HC-SR04, and a narrower beam. In practice, the black competition walls absorbed their 940 nm IR signal and consistently returned out-of-range readings at 300 mm. The HC-SR04 reflects off any surface regardless of color. We went with reliability over precision and made up the accuracy difference with software filtering (EMA on all three channels, plus a 5-sample median on the front channel to reject spikes before they can trigger a maneuver).

MPU-6050 IMU

The MPU-6050 gives heading and rotation data during cornering and recovery. The gyro Z axis is integrated each loop into anguloGyro, with a 1°/s deadband to suppress MEMS thermal drift on straights. On startup the firmware averages several hundred stationary samples to compute the gyro bias (calcGyroOffsets); if that offset comes back unusually large the firmware halves the integration scale as a safety net. The integrated heading is also sent back to the Pi in every acknowledgement so the vision side can dead-reckon obstacle positions (see §4.4).

BNO085 IMU (v2, in integration)

Why replace the MPU-6050. The MPU-6050 only gives a gyro rate. The ESP32 integrates it once per main loop, with a 1°/s deadband and a bias measured at boot. Our logs show what that costs:

  • The integrated heading over a full run came out 6.5% low: ≈1010° for the 1080° of 12 corners (§6.3 #6).
  • After every corner maneuver the heading carried a constant −7.5° ± 0.9° bias (ERR-23).
  • The integration accuracy depends on how regular the main loop is, and the loop is busy with sensors and serial traffic.

The BNO085 is a 9-axis sensor (gyroscope, accelerometer and magnetometer) that runs the sensor fusion on its own processor, with continuous bias calibration, and outputs a finished heading.

How we connect it. We use its UART-RVC mode. The sensor sends a 19-byte packet with yaw, pitch, roll and acceleration every 10 ms (100 Hz) over a single wire: BNO TX → ESP32 GPIO 25. Each packet carries a checksum. We chose this mode because it needs no driver library, keeps the IMU off the I²C bus that the four ToF sensors share, and lets the ESP32 just read the latest heading instead of integrating it. The test sketches BnoRvcTest and TofBnoTest report the packet rate, the longest gap, lost packets and checksum errors.

Acceptance before it gets control (log-only next to the MPU-6050 first):

  • ≥ 99% of packets at ~100 Hz on the car, with the motor running.
  • Total rotation over 12 corners within ±1% of 1080° (the MPU-6050 was 6.5% low).
  • Heading unchanged while the motor runs at standstill. The BNO085 includes a magnetometer, and a magnetometer sitting a few centimeters from a motor and a LiPo pack can be pulled by their magnetic fields. If this test shows drift with the motor on, we switch to the sensor's game rotation vector (gyro + accelerometer only, no magnetometer) over I²C, at the cost of using its driver library.
VL53L1X time-of-flight array (v2, in integration)

Layout:

SensorPositionUseXSHUT pin (ESP32)I²C address
FrontFront bumperDistance to the wall ahead: corner approach and the forward/reverse maneuver choiceGPIO 00x30
LeftLeft sideDistance to the side wallGPIO 150x31
RightRight sideDistance to the side wallGPIO 40x32
RearRear bumperReverse maneuvers: leaving the lot, reverse pivots and parking, which are blind todayGPIO 50x33

All four share the I²C bus (SDA 21, SCL 22) and all start at the same factory address (0x29). At boot the ESP32 holds every sensor off with its XSHUT pin, then turns them on one by one and gives each a new address. Test sketches: TofTest4 (4 sensors), TofId (tells an L0X from an L1X).

Why both ultrasonic and ToF

The inner walls of the WRO field are black, and that is the hardest surface for a distance sensor. The two sensor types fail against it in different, recognizable ways, so we keep both and let each one catch the other's failure:

HC-SR04 ultrasonicVL53L1X time-of-flight
Black wallSound reflects regardless of color ✔The black surface absorbs most of the 940 nm infrared. The return is weak: the reading drops out, or the range becomes wrong. Our VL53L0X lost the wall past ~70 cm (ERR-01), and other teams report ~80–100 cm usable with the L1X ✘
False readingsThe echo returns from anything inside a wide acoustic lobe, including the side wall at a grazing angle, plus multipath reflections. The front sensor reported a wall that wasn't there in ~20% of straight-line frames (ERR-19) ✘An optical cone with no echoes. Its size is set in software (region of interest), so it can be made to look only at the wall ✔
RangeUsable to ~119 cm with our timeoutNear field only (≤ ~80 cm) on a black wall
SpeedOne ping at a time, since sensors that fire together hear each other20 Hz each, all four in parallel

Planned cross-check rule. It runs log-only first, recorded next to the current behavior, before it gets control:

  • A ToF reading counts only if its range status is valid, it is ≤ 80 cm, and it is stable for 2 readings.
  • Front: if the two disagree by more than 15 cm and the ToF reading is valid, trust the ToF; the known failure on that side is the ultrasonic phantom. If the ToF is invalid or out of range, use the ultrasonic; the known failure there is a black-wall dropout.
  • Sides: if the ToF says "no wall" while the ultrasonic sees one closer than 100 cm, it is a black-wall dropout, so trust the ultrasonic.
  • Every disagreement is logged with both values, so the thresholds are tuned on recorded runs and not guessed.
Sensor placement and field geometry

Each position is chosen from the field dimensions in the rules: walls 100 mm high and black on the inside, pillars 50 × 50 × 100 mm, white floor mat.

SensorPlacementField geometry behind it
ToF × 4~50 mm above the floor, centered on the 100 mm wall heightThe VL53L1X sees a 27° cone by default. Mounted low, that cone hits the white floor at ≈4× its mounting height, and a bright floor easily wins over a dark wall. Teams who mounted them low saw exactly this. With a wide-and-short region of interest (16 × 4 detector cells ≈ 27° × 7°), the vertical half-angle is ≈3.4°. At 80 cm the cone spans ±4.7 cm, so at 50 mm height it stays inside the 0–100 mm wall.
Ultrasonic L / RSides, perpendicular to the straightThey read the wall parallel to the current straight. The inside sensor reads the opening that triggers a corner.
Ultrasonic F + ToF FFront bumper, on the centerlineThey read the wall ahead. Their distance decides when the stop-and-turn starts, and which maneuver is used (forward arc vs reverse pivot).
ToF rearRear bumperThe parking lot and the reverse pivot happen backwards, where v1 had no sensor at all.
CameraFront, ~20° down, wide-angle 120°Sees both pillar columns of the straight and the corner line on the same frame.
BNO085Center, near the rotation axisKeeps centripetal acceleration out of the fused heading.

3.3 PCB & wiring

A custom two-layer PCB is the vehicle's backplane: it distributes power and carries every signal line between the ESP32, the sensors and the motor driver, so there is no breadboard or flying-wire harness to work loose. This is what let the front ultrasonic go in in under 30 minutes (§1.1) — the header was already there. The full editable KiCad project is in electrical/WRO_RevA/.

Schematic (schemes/schematic.png):

KiCad schematic

The ESP32 DevKit (U1) sits at the centre. Battery voltage (~11.1 V, 3S) comes in at the VCC screw terminal (J1) and splits two ways: the motor driver takes it directly, and a MINI560 buck (V1, bulk caps C1–C4) drops it to the 5 V logic rail. The RDB-14450 driver (U2) takes PWM_MOTOR / AIN1 / AIN2 from the ESP32 and drives MOTOR_1/2 out to the screw terminal J5. The four HC-SR04s land on headers US1–US4 (5 V / TRIG / ECHO / GND); their 5 V echo lines return through a BOB-12009 level shifter (U3) that steps ECHO1–ECHO4 down to 3.3 V for the ESP32. The MPU-6050 (U4) is on I²C. The TO_PI header (J3) is the entire link to the Raspberry Pi — RX / TX for the V2 protocol, READY for the handshake, PRGN for the start button (SW1), plus 3.3 V / GND. Two status LEDs (D1 PWR, D2 READY) complete the operator interface from §4.7.

Populated board (schemes/pcb_render.png):

3D render of the populated PCB

Board outline (electrical/PCB_dimensions.png):

PCB outline and dimensions

The board is a custom non-rectangular shape (~55 mm at its widest) that nests into the chassis around the Raspberry Pi 4 and the drivetrain — the electronics-first packaging from §1.1 in physical form. The cut-outs and the mounting-hole row let the PCB, the steering and the sensor mounts share one footprint without stacking height.

v2 PCB — two-floor board (in design)

The v1 board is a single layer of components shaped around the Raspberry Pi 4. The v2 chassis is ≈7 cm shorter, the Pi moves to the top, and the robot gains four ToF sensors (each with its own XSHUT line), the BNO085 UART and a second regulator. All of that does not fit on one footprint, so the v2 board is designed as two stacked floors on standoffs:

FloorContentsWhy separate
Power (bottom)Battery input (XT60), switch and fuse, two Mini560 regulators (Pi / everything else), motor driverKeeps the switching regulators and motor currents, with their heat and noise, away from the signal lines. It is also the heaviest floor, so it sits low.
Logic (top)ESP32, level shifter, headers for 3 HC-SR04, 4 VL53L1X (I²C + XSHUT), BNO085 (UART), servo, start button and LEDs, the link to the PiAll signal connectors on one accessible floor

Status: schematic and layout in progress in KiCad. The v1 project in electrical/WRO_RevA/ remains the reference until RevB is fabricated. The wiring diagram will be updated with it.

3.4 Main computer — Raspberry Pi 5 (v2)

Why we upgraded. We profiled the Pi 4 running the real race code. The main Python thread was using 97% of one core, and the loop ran at 14–18 fps depending on the scene. Most of that time was spent on vision, not on the camera: ~5 ms capture, 17–22 ms color detection, 45–48 ms bird's-eye view and centerline. With the remote desktop client running, the Pi 4 also reached 84 °C and entered thermal throttling. A faster CPU attacks every stage at once.

Measured result. We ran the unmodified race runtime on the Pi 5, replaying a recorded Obstacle Challenge run as the camera input at 30 fps:

Raspberry Pi 4Raspberry Pi 5 (16 GB)
Vision loop rate~15.5 fps (same run, recorded live)40–41.5 fps, stable for 60 s
Time per frame~65 ms~25 ms
Temperatureup to 84 °C, throttled46 → 52 °C, no throttling (0x0)

The Pi 5 also has the official Active Cooler. Its fan is controlled by the firmware: it stays off below 50 °C and speeds up in steps up to 100% at 75 °C. The M.2 HAT+ is installed for a future NVMe SSD, which will mainly make storage more durable when recording a video of every run.

What the port required:

  • Per-frame constants. Many filters and confirmations in the runtime count frames and were tuned at ~14 fps. At 40 fps they would run almost 3× faster in real time. The loop also doesn't wait for a new camera frame. Before racing on the Pi 5 we either cap the loop at the old rate or rescale those constants.
  • Serial port. On the Pi 5, /dev/serial0 points to the debug UART connector, not to the GPIO header. The ESP32 link uses /dev/ttyAMA0 (GPIO 14/15).
  • GPIO. The original RPi.GPIO library does not support the Pi 5, so we use the drop-in rpi-lgpio package and the code stays the same.
  • Camera. The Pi 5 uses the smaller 22-pin camera connector, so the Camera v2 needs a 22-to-15-pin cable. The automatic camera detection did not recognize our module, so /boot/firmware/config.txt loads it explicitly (camera_auto_detect=0, dtoverlay=imx219,cam1). The capture pipeline must request format=BGRx; without it, the camera source fails to negotiate a format on the Pi 5's image processor (not-negotiated). BGRx comes straight from the image processor at 30 fps using ~2% CPU.
  • Live view without a monitor. The remote-desktop client used on the Pi 4 does not work on the Pi 5 desktop (Wayland). pure_pursuit/cam_web.py streams the camera (or the race HUD with --hud) to a browser, with the color-calibration controls.
  • OpenCV. It must be the system package (python3-opencv), because the pip wheel is built without the GStreamer backend that the libcamerasrc capture pipeline needs.

4. Software Architecture

4.1 System overview — two controllers, one link

Responsibility is split across two processors by hardware strength:

text
        RASPBERRY PI 4 (Python, OpenCV)                          ESP32 (Arduino / C++)
 ┌───────────────────────────────────────────┐    V2     ┌────────────────────────────────────┐
 │ Camera → BEV homography → floor centerline│   UART    │ readPiSerial()  →  parse V2        │
 │ Pillar detection (HSV) + corner-line track│  ──────►  │                                    │
 │ Rolling obstacle memory (dead reckoning)  │  115200   │ 6-state FSM                        │
 │ Pure Pursuit geometric controller         │           │  SIGUIENDO / GIRANDO / RECUPERANDO │
 │ RECUPERANDO trigger (measured state)      │  ◄──────  │  CRUCERO / MANIOBRA / TERMINANDO   │
 │ builds one V2 line per processed frame    │  ACK:V2   │ cascade PID (wall + gyro)          │
 └───────────────────────────────────────────┘   ang=    │ servo + motor PWM, HC-SR04, MPU    │
                                               est= dir= └────────────────────────────────────┘
  • The Pi decides where to steer: it turns the camera frame into a top-down view, extracts a drivable centerline, runs a Pure Pursuit controller against it, and reduces the result to a single normalized steering value plus a few status flags. It processes 1 of every 3 captured frames (~12–15 Hz effective).
  • The ESP32 decides how to drive: it owns the 50 Hz control loop, the finite state machine, corner detection, the recovery behaviour, and every actuator. In the Obstacle round it treats the Pi's steering value as the primary reference while Pure Pursuit is active, and falls back to its own wall + gyro PID if the Pi goes silent for more than 800 ms. In the Open round it ignores the Pi's steer altogether and runs on wall + gyro PID the whole time (§4.5).

Why not one processor? Real-time GPIO timing (ultrasonic pulses, servo/motor PWM, gyro sampling) and non-deterministic OpenCV latency don't coexist well on one core. Linux can't guarantee a µs-accurate pulse while an HSV pass is running; a microcontroller can't run OpenCV. Splitting them lets each run at its own natural rate, and a late UART packet just means the ESP32 reuses the last command instead of stalling. This trade-off is analyzed in Section 5.

Where to start reading the code: the Pi loop is pure_pursuit/runtime_nuevo.py (run() → per-frame block); the ESP32 loop is PurePursuit.ino (loop() → the switch (estado)). Every module is annotated in Section 8; tunables live in pure_pursuit/config.py.

4.2 Inter-controller protocol ("V2")

One line per processed frame, newline-terminated, 115200 baud. The rest of Section 4 refers to these fields by name.

Pi → ESP32:

text
V2,obs=+0.123,turn=0,state=pp,prio=1,mem=18,pp=1,pasado=0,intr=0
FieldMeaning
obsNormalized steering, steer_deg / 60, range −1…+1 (+ = right).
turnLegacy directional hint — always 0; turn direction is resolved on the ESP32 side.
stateHuman-readable label for the journal (e.g. pp, avoid_red).
prio1 = an obstacle is actively being avoided → ESP32 must not start a corner turn.
memFrames of obstacle memory still live → also blocks corner detection while > 0.
pp1 = Pure Pursuit steering is authoritative (suspend the wall PID).
pasadoOne-frame pulse: the Pi confirms the car has physically cleared an obstacle → enter RECUPERANDO.
intrInterior-pass flag (disabled by default).

ESP32 → Pi:

text
ACK:V2,ang=12.34,est=S,dir=L,...debug...
FieldMeaning
angIntegrated IMU heading anguloGyro (degrees); resets to 0 at each turn.
estFSM state — S SIGUIENDO, G GIRANDO or MANIOBRA, R RECUPERANDO, C CRUCERO.
dirTrack turn direction — ? until the first turn, then L / R.

4.3 Vision pipeline (Raspberry Pi — pure_pursuit/)

Entry point: pure_pursuit/runtime_nuevo.py. Per processed frame:

  1. Capture — a threaded grabber pulls frames from the Pi camera through a libcamera/GStreamer pipeline at 640 × 480 BGR, dropping stale buffers so the loop always sees the newest frame.
  2. Bird's-eye view (bev.py) — a homography (inverse-perspective mapping) warps the camera frame to a top-down 400 × 400 image at 2 mm/px. The homography comes from bev_calib.npz, generated once by calibrate.py from a 3 × 3 grid of 9 physical floor markers (RANSAC fit). We use 9 points, not the minimum 4: a 4-point fit is exact and can't detect a mis-click or extrapolate safely beyond the marked area, while 9 points let the solver average out click noise across the full range the centerline actually uses (from just ahead of the car out to ~550 mm).
  3. Pillar detection (vision.py) — HSV masks for red and green, then contour filtering by area, solidity (compact blob ≈ 0.7–0.9, painted line < 0.4) and aspect ratio (< 2.2) so the mat's coloured lines are not mistaken for pillars.
  4. Centerline (centerline.py) — a floor-colour mask in the BEV, minus inflated "keep-out" disks around each obstacle. The keep-out is asymmetric per the WRO rule: a red pillar inflates further to its left (car passes on the right), a green pillar further to its right. Rows are sampled bottom-to-top; each row blends the free-gap center with the WRO pass-side using a weight that ramps up as the car nears the can (not a binary switch). A 1-D moving average plus a per-step Δx clamp keep the path within the servo's curvature limit.
  5. Pure Pursuit (controller.py) — a geometric pure-pursuit controller in BEV pixel space. Look-ahead is adaptive: it shrinks from 100 px toward 78 px as the nearest can closes longitudinally, so the car keeps translating and arcs around the can instead of pivoting in place. Output is slew-limited to 6°/frame to kill frame-to-frame steering whip.
  6. Serialize — the steering angle is normalized (obs = steer_deg / 60) and packed into one V2 line with the status flags (§4.2).
mermaid
flowchart TB
    A["Capture — threaded grabber<br/>Pi camera 640×480 BGR, drops stale buffers"]
    B["BEV homography (bev.py)<br/>IPM warp to 400×400 top-down, 2 mm/px<br/>from bev_calib.npz (9-point RANSAC)"]
    C["Pillar detection (vision.py)<br/>HSV red/green + area + solidity + aspect ratio"]
    D["Centerline (centerline.py)<br/>floor mask minus asymmetric keep-out disks<br/>red inflates left, green inflates right<br/>pass-side weight ramps with distance"]
    E["Rolling obstacle memory (obstacle_memory.py)<br/>ego-motion: assumed speed + real IMU heading from ACK<br/>confidence decay, prune-on-pass"]
    F{"Measured RECUPERANDO trigger<br/>ARM / CLEAR / SKEW — see §4.4"}
    G["Pure Pursuit (controller.py)<br/>geometric, look-ahead 100 to 78 px adaptive<br/>slew-limited 6°/frame"]
    H["Serialize one V2 line<br/>obs = steer_deg / 60, plus prio / mem / pp / pasado"]
    A --> B
    B --> C
    B --> D
    C --> E
    E --> D
    E --> F
    D --> G
    G --> H
    F --> H
    H --> Z(["UART to ESP32 @ 115200"])
How the Pure Pursuit controller works

Pure Pursuit is a path-tracking method: instead of reacting to an error signal, the controller looks a fixed distance ahead along the path — the look-ahead — picks the point on the centerline at that distance, and computes the single steering angle whose turning arc, starting from the car's current pose, passes exactly through that point. Every frame the target point moves forward along the centerline and the car "chases" it, so the trajectory is always a smooth arc onto the path rather than a hand-tuned reaction curve.

text
          centerline (from BEV)                 look-ahead point picked at
        ·····•·····•·····•···•···•  ← target    distance  ld  along the path
                            ╲
                             ╲  arc the steering angle produces
              ┌───┐           ╲
              │car│────────────•   robot pose (rear axle = reference)
              └───┘
                 └─ α = bearing to target,  steer = atan2(2·L·sin α, ld)

Why it fits this problem:

  • The vision pipeline already produces a path (the centerline), not a point to servo onto — Pure Pursuit consumes that path directly.
  • The look-ahead is a single, physically meaningful tuning knob: short = cut hard toward the path (fast dodge), long = ease onto it (smooth cruise). That is exactly the behaviour the obstacle logic needs, so avoidance is folded into the same controller by shrinking the look-ahead near a can instead of adding a separate avoidance mode.
  • It degrades gracefully: a noisy or short path just moves the target point a little; there is no integrator to wind up and no error term to spike.
python
dx = target[0] - robot_x          # lateral offset to the look-ahead point (BEV px)
dy = robot_y - target[1]          # forward distance to it
ld = max(1.0, math.hypot(dx, dy)) # actual chord length
alpha     = math.atan2(dx, dy)                                   # bearing to the point
steer_rad = math.atan2(2.0 * C.WHEELBASE_PX * math.sin(alpha), ld)  # pure-pursuit arc
steer_deg = math.degrees(steer_rad)

if bev_obstacles:                                   # a can is in play
    steer_deg *= self._distance_steer_gain(...)     # ramp 0.30→1.0 as it closes
steer_deg = max(-C.MAX_STEER_DEG, min(C.MAX_STEER_DEG, steer_deg))
steer_deg = clamp(steer_deg, prev ± C.PP_STEER_SLEW_DEG)   # 6°/frame slew limit

adaptive_lookahead shrinks the look-ahead from 100 px toward 78 px, and _distance_steer_gain ramps the steering scale from 0.30 up to 1.0, both as the nearest can closes. Both key off the longitudinal distance to the can (forward gap), not the Euclidean one: a can still off to the side but level with the car used to keep those values relaxed, and the car drove straight past the point where it should have started turning. The WRO pass-side bias (right of red, left of green) is not handled here — it is already baked into the centerline by centerline.py, so the controller only has to follow the path it is given.

If bev_calib.npz is missing, the runtime falls back to a simple reactive PID on the pillar's x-position in the raw frame (RED_TARGET_PX / GREEN_TARGET_PX) so the car is never left without a controller.

4.4 Obstacle handling (Obstacle Challenge)

Rolling obstacle memory (obstacle_memory.py). The BEV only contains what the camera sees now; as the car closes on a can, the can leaves the bottom of the frame, its keep-out disc vanishes, and the centerline snaps back to center — cutting the corner onto the can. The memory fixes this: seen cans are stored as (x, y, colour, confidence) in robot-relative BEV coordinates and, every frame, the ego-motion is applied to every remembered can — forward travel from an assumed speed, rotation from the real IMU heading change in the ESP32 acknowledgement:

python
dheading = heading_deg - self._prev_heading          # real Δ from the ACK, degrees
ds_px    = (C.ROBOT_SPEED_MMS * dt_s) / C.MM_PER_PX  # assumed forward advance, BEV px
# a hard dodge rotates the car without translating it — shrink ds_px when |dheading| is large
ds_px   *= turn_brake(dheading)
self._advance(ds_px, dheading)     # each can: y += ds_px, then rotate −dheading about the robot

Fresh detections are merged in, unseen cans decay in confidence and are pruned once genuinely passed. The inflated keep-out therefore persists until the car has physically cleared the can. The heading_deg this relies on is exactly the value the ESP32 integrates for its own control (see §4.6) and echoes back — one shared heading, so the map rotates by the same angle the car actually turned.

"Mine" vs "beyond the corner" (corner_lines.py). The mat's orange corner lines are tracked row-by-row in the BEV. Each remembered can is classified as mine (on my straight, must be avoided) or beyond (on the next straight, ignore for now), with asymmetric hysteresis — quick to start avoiding, slow to stop — because starting to dodge is the safe side of a wrong call.

Far hint (far_hint.py). A PD controller on a pillar's offset in the raw camera frame (before it projects into the BEV range) nudges the steering to pre-center on a distant can, capped at ±12° so it can only hint, never dodge.

Mid-turn detector (mid_turn.py). While the ESP32 is turning, the rolling memory is disabled (its motion model assumes forward travel, which a pivot violates). This detector instead uses only the raw per-frame BEV projections and requires a same-colour can in a consistent position across several frames inside a close forward cone to "confirm" it. Phase 1 (current): observe and log only — it writes [MTURN] lines to the journal and does not yet change steering, so we can measure its reliability on-track before wiring it into the firmware.

Triggering RECUPERANDO from the obstacle memory

The problem. When the car has to swing wide around a can with no room to spare, it finishes the pass crooked — pointing 30–60° off the straight — and often with one wall out of ultrasonic range. At that exact moment the camera view is the least trustworthy (the centerline is short and skewed), so letting Pure Pursuit "straighten itself" from what it sees tends to over- or under-correct into a wall. The fix is to hand the wheel to the ESP32's wall + gyro PID (state RECUPERANDO) until the chassis is realigned — but only for a hard dodge. A gentle dodge with space to spare straightens itself fine and should not stop for a recovery.

The trigger (_measured_recup_trigger in runtime_nuevo.py) does not dead-reckon the can itself — it reads the state the obstacle memory and the IMU already provide, and needs three things to line up:

text
1. ARM   a real dodge is in progress:
         the centerline's avoidance weight near the car's axis has been
         ≥ RECUP_MEAS_ARM_W for RECUP_MEAS_ARM_FRAMES straight frames.
         On arming, snapshot heading_ref = current heading (the straight's heading).

2. CLEAR the memory no longer places any Red/Green can both far enough ahead
         of the axis AND close enough to the side to be in the way
         (going straight, the car's edge would clear it) — held for
         RECUP_MEAS_CLEAR_FRAMES frames (or just 1 if a corner is imminent).

3. SKEW  |heading − heading_ref| ≥ RECUP_MEAS_HEADING_DEG   (25°)
         → there is actually something to straighten.

ARM && CLEAR && SKEW  →  emit pasado=1  (one-frame pulse)  →  ESP32 enters RECUPERANDO
CLEAR but never SKEW for RECUP_MEAS_GENTLE_FRAMES  →  disarm quietly, no RECUPERANDO
mermaid
flowchart TB
    S(["Each processed frame"]) --> ARM{"Centerline avoidance weight near the car axis<br/>>= ARM_W for ARM_FRAMES consecutive frames?"}
    ARM -- no --> S
    ARM -- yes --> SNAP["Snapshot heading_ref = current heading<br/>(the straight's heading)"]
    SNAP --> CLR{"Memory places NO red/green can both far enough ahead<br/>of the axis AND close enough to the side to be in the way?<br/>held CLEAR_FRAMES frames (or 1 if a corner is imminent)"}
    CLR -- no --> HOLD["Keep dodging (pasado = 0)"]
    HOLD --> CLR
    CLR -- yes --> SKEW{"abs(heading − heading_ref) >= 25° ?"}
    SKEW -- "yes" --> FIRE["Emit pasado = 1 (one-frame pulse)<br/>trigger disarms — fires once per dodge"]
    SKEW -- "no, for GENTLE_FRAMES" --> DIS["Disarm quietly — the gentle dodge<br/>straightens itself, no RECUPERANDO"]
    FIRE --> ESP(["ESP32: SIGUIENDO → RECUPERANDO<br/>wall + gyro PID realigns the chassis"])

Condition 3 is what separates the two cases: same "can is now behind me" geometry, but only the crooked one triggers a recovery. The trigger disarms on fire, so it emits once per dodge — a can that lingers in memory while the ESP32 straightens can't re-fire it. The can positions it checks are the same (x, y) the memory maintains — corrected by fresh detections while the can is visible, and carried by the same ego-motion the centerline uses once it isn't (see the memory snippet above) — so the trigger and the path always agree on where the can is.

This replaced an earlier approach that anchored the can's position when first seen and dead-reckoned it forward with an assumed speed and a bicycle model; that anchor drifted 200–400 mm within 1–2 s and fired either early (nose into the can) or far too late.

4.5 ESP32 finite state machine (src/ESP32/PurePursuit/PurePursuit.ino)

text
enum Estado { SIGUIENDO, RECUPERANDO, GIRANDO, CRUCERO, MANIOBRA, TERMINANDO, INICIO, ESTACIONANDO, ESTACIONANDO_PUNTA };
mermaid
stateDiagram-v2
    [*] --> WAIT_PI: setup() blocks on READY
    WAIT_PI --> WAIT_FIRST_V2: READY acknowledged
    WAIT_FIRST_V2 --> SIGUIENDO: first V2 line (motor gated at 0 until here)

    SIGUIENDO --> RECUPERANDO: pasado=1, obstacle physically cleared [Obstacle]
    SIGUIENDO --> GIRANDO: corner detected, cooldown elapsed [Open]
    SIGUIENDO --> CRUCERO: straight clean, front sensor < FRONT_CRUCERO_CM [Obstacle]

    RECUPERANDO --> SIGUIENDO: heading settled or timeout, lane clear
    RECUPERANDO --> CRUCERO: heading settled or timeout, wall ahead [Obstacle]

    GIRANDO --> SIGUIENDO: reaches AngGiro, turn counted, heading re-zeroed
    GIRANDO --> TERMINANDO: 12th turn

    CRUCERO --> SIGUIENDO: a new "mine" obstacle appears, not yet committed
    CRUCERO --> MANIOBRA: front sensor at turn threshold (debounced), or CRUCERO timeout

    MANIOBRA --> SIGUIENDO: sub-sequence done, turn counted, new straight from 0
    MANIOBRA --> TERMINANDO: 12th turn

    TERMINANDO --> [*]: drive like SIGUIENDO for TERMINANDO_MS, then stop

    note right of MANIOBRA

This is the complete state machine as it stands on branch SectionTurning — the current firmware. One flag, const bool rondaObstaculos, selects the profile. false (Open Challenge): only SIGUIENDO / GIRANDO / RECUPERANDO / TERMINANDO are reachable and corners are the continuous GIRANDO arc. true (Obstacle Challenge): GIRANDO is replaced by the segmented CRUCERO → MANIOBRA sequence and the pasado-driven RECUPERANDO is enabled. RECUPERANDO never aborts on a new obstacle — it straightens the chassis first, then hands back to SIGUIENDO, or to CRUCERO if the corner is already in reach. The main branch still carries an earlier 3-state cut (SIGUIENDO / RECUPERANDO / GIRANDO); the SectionTurning merge is tracked as iteration log v3.0. WAIT_PI / WAIT_FIRST_V2 are the startup handshake (§4.7).

StateRole
SIGUIENDONormal driving. In the Obstacle round, steering = Pi's Pure Pursuit value, blended with a light gyro correction (weight 0.12) and, only on a clean straight, the wall PID (weight 0.30). In the Open round the Pi's steer is ignored entirely — steering is pure wall PID + gyro PID (see §4.5.1). Watches for the next corner and for obstacle flags from the Pi.
GIRANDOContinuous corner (Open round only). Servo held at full lock, motor speed ramped down in steps as |anguloGyro| grows, exits at |anguloGyro| ≥ AngGiro — 76° in the Open round (the continuous turn coasts the rest on inertia) vs. 90° for the Obstacle round. The first corner latches the track's turn direction from whichever wall opened up. 12 corners = 3 laps → TERMINANDO.
RECUPERANDO(Obstacle round) Entered on the Pi's pasado=1 pulse. Vision is handed off; wall PID + gyro PID (with widened limits) straighten the chassis back into the lane. Exits when the heading error settles (with a timeout safety net for corners where one wall legitimately reads "open").
CRUCERO(Obstacle round) Straight is clean and a corner is near (front sensor < 80 cm). The car drives straight on heading toward the wall: far away, vision keeps the centerline straight; once inside CRUCERO_GYRO_CM, control is pure gyro + wall PID. A new obstacle sends it back to SIGUIENDO.
MANIOBRA(Obstacle round) Replaces the continuous turn. At 30–60 cm from the wall a one-time decision is latched: turn direction = the side whose wall is open; forward arc vs. reverse pivot = chosen from the distance to the outer wall of the turn (tight against it → reverse pivot; room to swing → forward arc). A multi-phase sub-machine runs it, with motor-coast phases inserted between every direction reversal (plugging the H-bridge under load destroyed a TB6612 during testing). An optional short straight back-off afterward buys room on the new straight. Then it straightens, zeroes the heading for the new straight, counts the turn and returns to SIGUIENDO.
TERMINANDOEntered automatically after the 12th turn instead of braking on the spot. Drives exactly like SIGUIENDO (same controller, but corner detection disabled) for TERMINANDO_MS (~1 s, tunable) so the car rolls forward into the start area, then cuts the motor and ends the race. Keeps the finish inside the start section instead of wherever the last corner happened to end.

The turn-direction is latched once (all corners of a WRO track turn the same way); the forward-vs-reverse choice is made fresh at every corner from the distance to the outer wall of the turn (decidirManiobra()):

cpp
// outer wall = the one that is NOT the opening (right turn → left wall, and vice-versa)
long distExt = maniobraGirarDer ? distL : distR;
maniobraReversa   = (distExt >= HUG_CM);                    // room to swing → reverse pivot
maniobraRetroceso = (distExt >  MANIOBRA_BACKOFF_MIN_CM);   // slack → short back-off after

One flag switches the whole driving profile: const bool rondaObstaculos at the top of PurePursuit.ino.

Open Challenge (false)Obstacle Challenge (true)
Steering sourceESP32 wall PID + gyro PID only — the Pi's Pure Pursuit steer, prio/mem/pasado flags are all ignoredPi Pure Pursuit centerline; PID as blend / fallback / RECUPERANDO
Corner turncontinuous GIRANDOCRUCERO → MANIOBRA segmented
Turn target AngGiro76° (the continuous turn coasts the rest on inertia)90°
Motor PWM ceiling MOTOR_MAX180 — fast; the in-turn speed ramp does the slowing100 — slow, for fine maneuvers
RECUPERANDO / obstacle handlingnever enteredactive

TERMINANDO and the cascade PID run in both.

4.5.1 Open-round corner hardening

With the Pi's vision out of the loop, three guards keep the continuous turn honest:

  • giroArmado — corridor arm. detectarEsquina() is not allowed to fire a turn until the car has first confirmed it is inside a corridor: both side walls < 100 cm for PASILLO_FRAMES (3) consecutive frames. A wide reading in the start zone therefore can't trigger a false first turn. Once armed it stays armed for the whole run, so real corners are never delayed by it (unlike a fixed time lockout).
  • Front-wall approach slow-down. When the front sensor sees the end wall closer than FRONT_SLOWDOWN_CM (60 cm), speed drops to VEL_APROX_CERRADA (140) so detectarEsquina() gets a clean read of which side opens before the car is on top of the corner.
  • marchaIniciada timer re-anchor. The start-guard timer (timeStart) is reset to the instant the car actually starts rolling — not to when READY arrived seconds earlier — so its window is measured from roll-off.
4.5.2 States added for the national final: start from the lot and parking

The diagram above shows the six driving states. Three more were added between 2026-09-07 and the national final:

StateEntered whenWhat it does
INICIOThe Pi sends inicio=1 (the car starts inside the parking lot)Scripted S-shaped exit from the lot, gyro-checked, then SIGUIENDO
ESTACIONANDOLast corner, parking mode PARK_PARALELOParallel parking in reverse inside the magenta lot
ESTACIONANDO_PUNTALast corner, parking mode PARK_PUNTASimpler nose-in partial parking (fallback)
  • Start in the lot. While disarmed, the Pi measures the share of magenta in the frame. When the button is pressed it decides once whether the car is inside the parking lot, and sends inicio=1 if so. The ESP32 then runs INICIO: it swings out of the lot, drives straight, counter-steers back to the track heading, and backs up briefly to square up before the first straight.
  • Parking. After the last corner the car follows the outer wall. It detects the lot from the side ultrasonic profile (wall → gap → wall), and the camera confirms the magenta walls. Then it parks in reverse in ESTACIONANDO. During parking, the heading reference is re-measured against the wall to cancel the gyro drift collected over 3 laps (PARK_TRIM_*). Runs 1025, 1052 and 1064 produced perfect parallel parks, and we keep their constants as the reference set.

4.6 Cascade PID (always running underneath)

Even in Pure Pursuit mode the ESP32 computes its dual cascade PID every loop — it is the fallback, the RECUPERANDO/CRUCERO controller, and the blend term in SIGUIENDO.

text
                ┌────────────────────┐   heading    ┌────────────────────┐
  distL─distR ─►│     OUTER PID      │─ setpoint ──►│     INNER PID      │──► servo
                │   (wall centering) │              │  (heading control) │
                └────────────────────┘              └────────────────────┘
                         ▲                                    ▲
                  HC-SR04 readings                    MPU-6050 heading

The single-loop error = distL − distR controller it replaced failed past ~30° of yaw: the HC-SR04's conical beam hits the wall obliquely, both sensors over-report, the difference sits near zero while the car drifts into a wall. The outer loop turns lateral wall error into a target heading; the inner loop drives the servo to that heading using the IMU, which doesn't care about beam geometry.

Tuned gains: KpWall 1.0 / KiWall 0.0 / KdWall 1.2, KpGyro 2.0 / KiGyro 0.0 / KdGyro 0.5. Both integral terms are disabled on purpose — integral built up on long straights and released as a large steering impulse at corner entry, overshooting into the opposite wall. The derivative terms give enough steady-state correction on their own. Raw ultrasonic reads pass through an EMA filter (alpha = 0.85) before the PID.

cpp
// OUTER: lateral wall error → steering contribution (Ki = 0)
errorWall  = constrain(distL - distR, -50, 50);
outputWall = KpWall*errorWall + KdWall*(errorWall - prevErrorWall)/dt;

// INNER: heading error vs. the straight's reference heading (Ki = 0)
errorGyro  = anguloObjetivo - anguloGyro;
outputGyro = KpGyro*errorGyro + KdGyro*(errorGyro - prevErrorGyro)/dt;

// SIGUIENDO with Pure Pursuit active: the Pi's steer leads, PID only trims a clean straight
servo = centroServo - (steerDeg - outputGyro*PP_GYRO_BLEND - outputWall*PP_WALL_BLEND);
// fallback / RECUPERANDO / CRUCERO-near-wall: PID alone
// servo = centroServo + (outputWall + outputGyro);

Heading is integrated on the ESP32 from the gyro Z axis, with the 1°/s deadband that keeps MEMS thermal noise from drifting the straight-line heading:

cpp
float gz = mpu.getGyroZ() / gyroScale;
if (abs(gz) < 1.0) gz = 0;        // 1°/s deadband
anguloGyro += gz * dt;            // this is the value echoed back to the Pi

4.7 Startup handshake

  1. Pi lights the LED on GPIO 27 — "Pi is up".
  2. Pi waits for the start button on GPIO 17.
  3. Camera warm-up (~40 frames discarded to settle exposure).
  4. Pi sends READY ×3; the ESP32 has been blocking in setup() waiting for it.
  5. ESP32 replies ACK:READY, then holds the motor at zero until the first real V2 line arrives (a gate so the car never rolls forward on the fallback PID before Pure Pursuit is actually streaming). On the first frame it then rolls, marchaIniciada re-anchors the start-guard timer to that instant.
  6. Main loop runs until 12 turns are counted, then TERMINANDO drives ~1 s more into the start area and stops.
mermaid
sequenceDiagram
    participant Pi as Raspberry Pi
    participant ESP as ESP32
    Pi->>Pi: Light LED on GPIO 27 ("Pi is up")
    Pi->>Pi: Wait for start button (GPIO 17)
    Pi->>Pi: Camera warm-up (~40 frames discarded)
    Note over ESP: setup() is blocking, waiting for READY
    Pi->>ESP: READY x3
    ESP->>Pi: ACK:READY
    Note over ESP: Motor held at 0 until the first V2 line
    Pi->>ESP: First V2 line (obs + flags)
    Note over ESP: Car rolls — start-guard timer re-anchored to this instant
    loop Every processed frame (~12-15 Hz)
        Pi->>ESP: V2 line — obs, prio, mem, pp, pasado
        ESP->>Pi: ACK:V2 — ang (heading), est (S/G/R), dir (?/L/R)
    end
    Note over ESP: 12 turns counted, then roll ~1 s into start zone and stop

4.8 Development status

ModuleChallengeStatus
BEV homography + 9-point calibration toolbothComplete
Floor centerline extractionbothComplete
Pure Pursuit geometric controllerbothComplete, track-tuned
ESP32 cascade PID + fallbackbothComplete
Continuous corner turn (GIRANDO)OpenComplete, track-tuned
Open-round pure-PID mode + corner hardening (giroArmado, approach slow-down)OpenImplemented, not track-tuned
Return-to-start finish (TERMINANDO)bothImplemented, not track-tuned
Pillar detection (HSV + shape filter)ObstacleComplete
Asymmetric WRO keep-out in centerlineObstacleComplete
Rolling obstacle memory (dead reckoning)ObstacleComplete, track-tuned
Corner-line "mine / beyond" classifierObstacleComplete
Measured-state RECUPERANDO triggerObstacleComplete, track-tuned
Segmented turn (CRUCERO → MANIOBRA)ObstacleRaced at the national final; forward/reverse hysteresis added after it (ERR-22)
Mid-turn cone detectorObstaclePhase 1 — logging only
Start from the parking lot (INICIO)ObstacleRaced at the national final
Parallel parking (ESTACIONANDO)ObstacleWorking in testing — perfect parks in runs 1025, 1052, 1064
Floor-referenced color correction + ratio testsbothComplete (ERR-15, ERR-17)
Raspberry Pi 5 portbothMeasured on the real Pi 5 (2026-11-06): 23.5 ms per frame mean, p95 32 ms (≈40 fps); route replan 59–70 ms (§4.9)
Route mode — digital map + planned route + U-turn + parallel park (§4.9)ObstacleValidated in the digital twin (47/48 full races); not yet run on the car
VL53L1X ToF sensorsbothBench testing (§3.2)

4.9 Route mode (v2) — a planned route instead of reactive steering

Why. The v1 controller steers toward what the camera sees now. Every pillar seat in the Obstacle Challenge is one of 24 known positions, so once a pillar has been seen its position on the mat is known. v2 keeps a digital map of the mat and plans the whole lap at once, then drives it as fast as the curvature and the remaining unknowns allow.

How it works.

  1. Map (digital_map.py): each pillar detection is projected through the BEV calibration and snapped to its seat. A seat not seen yet stays unknown.
  2. Planner (ring_route.py): dynamic programming over 96 stations per lap × lateral offsets every 20 mm. Hard constraints: the real footprint of the car (rectangle, rear-axle reference) keeps a minimum clearance to pillars, walls, island and parking walls; minimum turning radius; side rule (red on the right, green on the left). Cost: travel time + curvature² + a penalty for small clearance. In lap 1 an unknown seat is an obstacle with no side, and the route passes close to it so a late reveal changes the route by ~300 mm instead of ~550 mm. The core loop is a native C kernel.
  3. Follow (route_mode.py + ESP32): the Pi uploads the route as points (RTB/RTP/RTE lines over the V2 link at 460800 baud). The ESP32 follows it with pure pursuit on its own odometry (encoder + IMU), so steering does not wait for the camera. The Pi sets the speed from a profile (lateral-acceleration and braking limits, slower near pillars).
  4. Finish: after lap 3, a 180° U-turn and a parallel park in the bay, both planned in the same frame.

Compute latency — measured, then designed around. We ran a full race of the digital twin on the real Pi 5 and timed it:

Mac (dev)Raspberry Pi 4 (v1)Raspberry Pi 5 (v2)
Vision + control per frame5.4 ms60 ms (≈16 fps)23.5 ms mean, p95 32 ms
Route replan11–36 msmedian ≈190 ms59–70 ms, peak 223 ms
First plan (fills the planner caches)146 ms2.6 s1.95 s

Running the planner on 4 OpenMP threads was slower than 1 thread, so it runs single-threaded. Feeding these delays into the twin showed that the route logic had been tuned for an instantaneous planner: with the Pi 5 latency only 18 of 48 races finished clean. Three changes fixed it:

  • Precompute at boot. The 1.95 s first plan runs when the program starts, before the ready LED turns on, so it never counts against race time.
  • Plan in a background thread on the car, so vision keeps running while the planner works (before, the camera froze during each plan).
  • Lock only ~150 mm (2 stations) of the old route ahead of the car instead of ~525 mm, so a new pillar changes the route sooner.

Result: 40/48 clean with Pi 5 latency (repeat: 39/48), and with no latency the race is unchanged (47/48, median 37.26 s). Measurements in §6.3; design notes in docs/MODO_RUTA.md and docs/HANDOFF_PERFIL.md.


5. Systemic Thinking & Engineering Decisions

5.0 Design constraints

Every decision in this section was made inside these limits:

ConstraintSourceLimitHow it shaped the robot
SizeRule 11.1≤ 300 × 200 × 300 mmWe stay far below it on purpose (v2 ≈17 cm long) to have room to dodge and park (§2.6)
WeightRule 11.2≤ 1.5 kg564 g in v1; light enough that the N20 at 100:1 accelerates cleanly
DriveRule 11.3One driving axle and one steering actuator; no differential driveAckermann rack-and-pinion + a printed rear differential
No radio during roundsRule 11.10Wi-Fi, Bluetooth and Tailscale must be offAll debugging is offline: a recorded video and journal per run. The live view is used only in practice
No manual calibration at the startRule 9.9Nothing set by hand on the tableGyro bias measured automatically at boot; camera and color calibration done in the practice time
Black wallsField rules 13.3–13.4Dark, IR-absorbing wallsUltrasonic + ToF cross-check (§3.2)
Round time and rankingRules 9.1, 10.7–10.83 minutes; points first, time breaks tiesPoints over time: stop-and-turn corners (§4.5)
ProcessingRaspberry Pi 414–18 fps, compute-bound (97% of one core)Raspberry Pi 5: 40 fps on the same pipeline (§3.4)
HeatEnclosed Pi 484 °C → thermal throttlingPi 5 + Active Cooler, mounted on top (§2.6)
Power qualityPi undervoltageA 0.3 V drop throttled the CPU22 AWG wiring; a dedicated regulator for the Pi in v2 (§3.1)
Battery voltageOpen-loop motor (v1)Behavior changes with charge levelRace window of 11.70–12.15 V; v2 encoder motor mounted for closed-loop speed
TimeCalendar~11 weeks between the national (09-19) and international (12-08) finals; documentation due 11-24Every change must be checkable on recorded runs (replay) before it gets track time
BudgetTeamv1 ≈155 USD; the Raspberry Pi 5 alone is ≈410 USDThe Pi 5 is the big v2 expense; the sensors were picked from the low-cost, widely documented ones (VL53L1X, BNO085)

5.1 Subsystem interaction map

mermaid
flowchart LR
    subgraph PI["Raspberry Pi 4 — vision and planning"]
        CAM["Pi camera"] --> BEV["BEV homography"]
        BEV --> PD["Pillar detection (HSV)"]
        BEV --> CL["Centerline<br/>asymmetric keep-out"]
        PD --> OM["Rolling obstacle memory"]
        OM --> CL
        OM --> TRG["RECUPERANDO trigger"]
        CL --> PP["Pure Pursuit"]
    end
    subgraph ESP["ESP32 — real-time control"]
        OUT["OUTER PID<br/>wall centering"] --> INN["INNER PID<br/>heading via IMU"]
        FSM["Finite state machine"]
        SEG["CRUCERO / MANIOBRA<br/>segmented turn"]
        INN --> ACT(["servo + motor PWM"])
        FSM --> ACT
        SEG --> ACT
    end
    USLR["HC-SR04 left / right"] --> OUT
    USF["HC-SR04 front"] --> SEG
    IMU["MPU-6050"] --> INN
    PP -- "obs (V2 @ 115200)" --> FSM
    TRG -- "prio / mem / pasado" --> FSM
    IMU -- "ACK: heading" --> OM

The IMU heading is the shared currency: the ESP32 integrates it for its own control and ships it back so the Pi's obstacle memory can rotate its map by the exact same angle. Everything the Pi decides reaches the ESP32 as four flags and one number; everything the ESP32 knows about its own state reaches the Pi as three fields. Neither side can stall the other.

5.2 Key engineering trade-offs

Trade-off 1 — one processor vs. two. One ESP32 would remove the UART protocol, the Linux boot time and the sync logic. But real-time computer vision breaks single-core timing: a 640 × 480 HSV pass is 8–15 ms on the Pi 4, and running it alongside µs-accurate GPIO pulses gives non-deterministic jitter. Splitting by hardware strength (Pi = vision + planning, ESP32 = timing + actuation) lets each run at its own rate; a delayed packet just means the ESP32 reuses the last command. The cost — a protocol to maintain and two codebases — was worth deterministic control.

Trade-off 2 — VL53L0X ToF vs. HC-SR04 ultrasonic. ToF wins on paper (±3 mm vs ±15 mm, narrow beam). But the WRO field's matte-black walls absorbed the 940 nm IR and returned out-of-range at 300 mm in our tests. Ultrasonic reflects off anything. We chose reliability and closed the accuracy gap with EMA filtering, a front-channel median filter, and the cascade PID.

Trade-off 3 — reactive steering vs. geometric Pure Pursuit. The first vision controller steered proportionally to the pillar's pixel offset. It over-reacted close in and under-reacted far out, and had no model of the car's path. Pure Pursuit against a BEV centerline gives a geometrically correct steering angle for a chosen look-ahead, and the look-ahead becomes a single tuning knob for "how hard to dodge". The cost is the BEV calibration step; the payoff is predictable arcs instead of hand-tuned reaction curves.

Trade-off 4 — forgetting a can when it leaves the frame vs. a rolling memory. The honest, stateless option is to only avoid what the camera sees now — but that cuts the corner onto a can the moment it drops out of view. The rolling memory keeps the keep-out alive using dead reckoning (assumed speed + real IMU rotation). The risk it adds — a "ghost" can from accumulated error — is bounded by confidence decay and a prune-on-pass rule, and is the safer failure (dodge a can that's already gone vs. clip one that's still there).

Trade-off 5 — continuous turn vs. segmented stop-and-maneuver (Obstacle round). A continuous 90° arc is fast and simple and works well in the Open round. In the Obstacle round, a can placed near the corner mouth turns that blind arc into a coin-flip. The SectionTurning design trades speed for certainty: cruise straight to a known distance from the wall (front sensor), stop, then run a deterministic maneuver — a forward arc if there's room, a reverse pivot if the car is tight against the outer wall. It is slower, but every corner becomes repeatable, which is the same principle that drove the 100:1 gear choice.

Trade-off 6 — forward arc vs. reverse pivot inside MANIOBRA. A forward arc needs clear space ahead to swing through; a reverse pivot needs the car close to the wall first. Rather than pick one, the firmware measures the distance to the outer wall of the turn and chooses per corner, with a reverse-timeout that bails out into a forward finish if the pivot stalls.

5.3 Iteration log

Structural changes and the tuning passes that revealed something — routine per-run parameter tuning in config.py between track sessions is not listed. Each row links to the commit that introduced the change. Status: Shipped (on main, track-validated) · On branch (implemented, still tuning) · Superseded (replaced by a later row) · Reverted (tried on track, backed out).

A dated, phase-by-phase account of the same history — including the pre-repo design and per-peripheral bring-up work — is in the Engineering Journal.

StageDateChangeWhy it changedEvidenceStatus
Mechanical + PCB2026-04-13 → 04-24Chassis, rack-and-pinion steering, printed differential and power PCB, designed from scratchNew vehicle every season283078e … 51ea239Shipped
First firmware2026-05-09Single-loop PID on distL − distR, VL53L0X ToF ×2, 3-state FSM (Controller_PI.ino)First open-round lap61544cbSuperseded
v1.1 — ToF → ultrasonic2026-05Both VL53L0X replaced with HC-SR04ToF lost the black wall past ~70 cm — ERR-0161544cb eraShipped
v1.2 — remove the integrators2026-05 → 06Ki = 0 on both PID loopsIntegral wound up on the straights and released as one impulse at corner entry → overshoot into the far wallController_PI.ino historyShipped
v1.3 — cascade PID2026-05 → 06Outer loop (wall error → target heading) + inner loop (heading → servo, via IMU)The distL − distR error goes blind past ~30° of yaw — ERR-02Controller_PI.ino historyShipped
Camera integration2026-05-23Pi camera, track-edge detection, BEV calibration tool (calibrate.py)Lane geometry the ultrasonics can't see21fe8df, 5797487Superseded
Two-controller split + deploy infra2026-06-08 → 06-09Pi ↔ ESP32 over UART; wro-runtime.service, VNC, push-to-deploy CIOpenCV latency and µs GPIO timing can't share one core (§5.2)69f82a9, a065d78Shipped
v2.0 — Pure Pursuit + centerline2026-06-13 → 06-22BEV homography → floor centerline → geometric Pure Pursuit (pure_pursuit/)Reactive pillar-offset PID had no path model — over-reacted near, under-reacted far95f3744, e494d8c, 556266bShipped
Camera lens FOV 63° → 120°2026-07 → 08-07Wide-angle NoIR lens (swapped over the July break); on return, pinned white-balance (awb-enable=false colour-gains=<1.2,1.5>) and re-tuned the obstacle RGB rangesNeeded more forward range for the obstacle round; the wide lens has no IR-cut filter, so the raw image had a heavy red cast — ERR-03945c2f1Shipped
v2.1 — offline sim2026-08-11Kinematic bicycle sim (pure_pursuit_sim.py, 520 lines) + runtime_nuevo.pyTune controller logic without track time0a2c5d2Shipped
v2.2 — BEV calibration 4 → 9 points2026-08-13RANSAC fit over a 3×3 marker gridA 4-point fit is exact — no way to reject a mis-click or check reprojection errordaf1e03Shipped
v2.3 — corner-line detection2026-08-17 → 08-19Orange / blue ground-line tracking in the BEVTurn trigger + a "my straight vs. the next one" boundary for obstaclesd3a611e, 8edc1b8Shipped
v2.4 — wall-aware steering (ParedCenterline)2026-08-20 → 08-21Centerline biased by ultrasonic wall distance; V2 protocol fixesCenterline alone drifted toward the outer wall on wide cornersmerges f5066e1, 24b2ec7Shipped
Open round validated2026-08-28—10 complete autonomous runs from varied start positions and field configs → focus moved to the Obstacle Challenge§6.2Shipped
v2.5 — rolling obstacle memory2026-08-24 → 08-27Seen cans kept in a robot-relative map, advanced by assumed speed + real IMU heading from the ACKCan leaves the frame → keep-out vanishes → centerline cuts the corner onto ita41ac0e, 3c96abf, 57d3218Shipped
v2.6 — hot start + run recording2026-08-28Pipeline runs disarmed during the button delay; ESP32 gated on the first V2 line; MJPG .avi HUD capture from button-pressCold camera/serial cost ~2 s at the start; every run now leaves a reviewable artifact3245c1c, 2355caf, f257371Shipped
v2.7 — undervoltage fix → frame-rate rescale2026-08-28Re-fed the Pi through 22 AWG leads (was dropping 0.3 V PCB→Pi → brown-outs, garbled frames); loop went ~7 → ~14 Hz; re-scaled every per-frame knob (slew, recovery frames, look-ahead floor)Half the tunables were calibrated at 7 Hz and were now firing twice as fast — ERR-08e4ca4f9, 1a19cdbShipped
v2.8 — pivot-trap root cause2026-08-28 → 08-29LOOKAHEAD_MIN_PX 60 → 78 (60 saturated the PP geometry); adaptive look-ahead + steer-gain re-keyed on the longitudinal gap; forget_color_obstacles() on pass so the centerline un-bendsNear a can the steer term hit ±0.9 (≈ full lock) → the car pivoted in place instead of arcing; y never advanced, RECUPERANDO never armed — ERR-061daf563Shipped
v2.9 — RECUPERANDO: anchor → measured state2026-08-28 → 08-29Retired the geometric dead-reckoning anchor; the trigger now reads the centerline avoidance weight, a heading snapshot, and the memory's own "is a can still in the way" test (ARM / CLEAR / SKEW)The anchor integrated an assumed linear speed and drifted 200–400 mm in 1–2 s whenever the car had to turn hard — ERR-07f24c547 → 25d0565 → 52549c8Shipped
v2.10 — turn-direction from the orange line2026-08-31Direction latched from the orange corner-line slope during the run, not pre-setA pre-set direction is one more thing to get wrong at check-ina72a751, e641817Shipped
v2.11 — exterior cone at the corner mouth2026-08-31A can right at the corner: drive straight past it, then turnThe blind turn arc would sweep into it4e5ca40Shipped
v2.12 — camera-safe service restart2026-08-31CI + ops use stop → sleep 4 → start, never systemctl restartrestart doesn't release the CSI device — camera wedges, LED stays dark9aff6c9Shipped
v3.0 — segmented turns (SectionTurning)2026-09-01Obstacle round only: GIRANDO → CRUCERO (cruise to a set distance on the front sensor) → MANIOBRA (forward arc or reverse pivot from outer-wall distance); motor-coast phase before every direction reversalA can at the corner mouth makes a blind 90° arc a coin-flip; a missing coast delay had already killed a driver + a motor — ERR-049219f17 (+386 lines to .ino)On branch
v3.1 — mid-turn cone detector2026-08-31mid_turn.py — raw per-frame BEV projections (rolling memory is off during a pivot); Phase 1: log onlyA can first seen during the turn ends up beside the car afterwards → clipped6b0b5c7On branch (logging)
v3.2 — Open round runs pure PID2026-09-03 → 09-04Open round ignores the Pi steer — wall + gyro PID only; per-round AngGiro / MOTOR_MAX; giroArmado corridor-arm; front-wall approach slow-down; TERMINANDO finishOpen round doesn't need vision and was inheriting obstacle-round speed caps; a wide start-zone reading latched a false first turn — ERR-05626fc91, 13e05c1On branch
v3.3 — gyro heading-hold by default2026-09-05On a clean straight the gyro steers; vision steers only while a pillar of ours is present. RECUPERANDO made non-interruptible; proportional wall override (wallPanic)Small dodges left the chassis 20–30° crooked and the car drifted into a wall (runs 679–690); run 700 = first clean 12-corner run9c4b75e eraShipped
v3.4 — start from the parking lot (INICIO)2026-09-09Pi measures the magenta share at the button press and sends inicio=1; ESP32 drives a scripted S-exitThe Obstacle Challenge may start inside the lot6a713e3Shipped
v3.5 — floor-referenced color correction2026-09-12Per-frame gains so the white mat matches a reference colorA darker room pushed the orange tape into the red range — ERR-157bd353fShipped
v3.6 — camera check before arming2026-09-14Start blocked (LED off) until the camera delivers real framesRun 860 drove 19 s with a blind camera — ERR-12486cc4cShipped
v3.7 — obstacle-memory merge guard2026-09-15A remembered pillar can't "reappear" where it physically couldn't beTwo reds across a corner merged into one (run 954) — ERR-218bfe4d0Shipped
v3.8 — red range for the new venue + B/R test2026-09-16Red hue 168–179 plus a blue/red ratio test against the pink wallsNew venue: red pillars not detected at all (run 1013) — ERR-14e3784a8Shipped
v3.9 — parallel parking2026-09-12 → 09-17Lot found from the side-ultrasonic profile, reverse parallel park, heading trimmed against the wall15-point parking; perfect parks in runs 1025, 1052, 1064cf28a0f, 8ef47d0Shipped
Release v1.0-nacional2026-09-19Code raced at the national final — 1st place—d5cc66dReleased
v3.10 — ratio tests + corner hysteresis2026-09-22RED_GR_MAX, GREEN_S_MIN_MED; forward/reverse decision with ±6 cm hysteresisStrong light: tape read as red, floor as green (run 1190) — ERR-17; maneuver flip at the boundary (run 1188) — ERR-2296145baShipped
v4.0 — steering Ackermann fix + 19-tooth pinion2026-10-06Rack joints 43 → 47 mm, tie rods 18.13 mm, pinion 14 → 19 teethAnti-Ackermann (39.5° / 42.8°) and only ~37° of steering — §2.4844195eValidated in CAD
v4.1 — Raspberry Pi 5 + camera calibration2026-10-06 → 10-07Pi 5 16 GB + Active Cooler; format=BGRx capture; lens-shading table for our lensPi 4 compute-bound at 14–18 fps and throttling at 84 °C; magenta ring on the Pi 5 — §3.4844195eOn branch
v4.2 — VL53L1X ToF ×42026-10Front, left, right, rear on one I²C bus with XSHUT re-addressingFront ultrasonic phantom echoes — ERR-19844195e (test sketches)Bench test

5.4 Risk analysis

RiskLikelihoodImpactMitigation
HC-SR04 spike readingMediumMedium — brief PID disturbanceEMA on all channels; 5-sample median on the front channel; cascade inner loop dampens
Gyro drift over 3 lapsLowMedium — heading offset grows1°/s deadband; heading zeroed after every turn; startup bias calibration
Camera mount shifts after BEV calibrationLowHigh — warped top-view, wrong centerlineRigid printed camera frame; recalibrate if the mount is touched; reprojection-error check in calibrate.py
Can leaves FOV mid-dodge → ghost obstacleMediumMedium — phantom keep-outConfidence decay; prune-on-pass; memory disabled during turns
UART packet delayed by OpenCV loadMediumLow — one stale commandESP32 reuses last command; 800 ms timeout → autonomous wall+gyro fallback
Corner missed / mis-countedLowHigh — wrong lap count or directionConservative thresholds; 2 s cool-down; prio/mem block detection while dodging; front-sensor debounce in the Obstacle round
False first turn from a wide start-zone reading (Open round)MediumHigh — wrong direction latched for the whole rungiroArmado: corner detection stays disabled until both walls read < 100 cm for 3 frames; timers re-anchored to roll-off
MANIOBRA runs the car into the outer wallMediumHigh — DQForward/reverse chosen from measured outer-wall distance; reverse-timeout fallback; optional post-maneuver back-off
H-bridge damage from direction reversal under loadLow (mitigated)High — dead driverMotor-coast phase inserted before every direction change (learned the hard way)
Servo driven into its end stopLowLowFirmware clamps servo command to 20°–150°

5.5 Failure & Incident log

Post-mortems for the failures that changed the design — what happened, the confirmed or suspected root cause, and what shipped in response. Several of these are the "learned the hard way" behind a row of the risk table in §5.4.

ERR-01 — VL53L0X lost the black wall past 70 cm
First seen2026-05, first wall-following bring-up
SetupTwo VL53L0X, one per side — the same left/right wall-distance job the HC-SR04s do now.
SymptomAgainst the matte-black outer wall the effective range collapsed: past ~70 cm the sensor stopped returning correct distances. White walls read to spec.
ImpactNo usable lateral reference on the black-walled portions of the track — roughly half the perimeter.
Root causeThe 940 nm IR is absorbed by the matte-black surface; too little returns for a time-of-flight solve. A single sensor on the bench reproduced it, so not a wiring or I²C fault.
FixSwitched both channels to HC-SR04 ultrasonic (61544cb era) — sound reflects off any surface regardless of colour. Traded ±3 mm for ±15 mm and closed the gap in software (EMA on all channels, a 5-sample median on the front channel, the cascade PID).
StatusResolved. Trade-off in §5.2.
ERR-02 — wall error goes blind at high yaw
First seen2026-05 — one of the earliest problems, open-round bring-up
SymptomOn corner entry and recovery the car kept drifting into a wall even though the PID output stayed small and stable.
Root causeThe HC-SR04's ~15° beam cone hits the wall obliquely once the chassis is yawed; both sensors over-report by similar amounts, so distL − distR sits near zero while the car is visibly crabbing toward one wall. This is inherent to the sensor geometry and is still true today.
FixThe cascade PID stops the car acting on the blind error: the outer loop turns lateral wall error into a target heading, the inner loop drives the servo to that heading from the IMU (§4.6). At high yaw the wall term is unreliable but the inner loop is still steering on a good heading signal, so the car tracks true and re-centres once the walls read cleanly again.
StatusMitigated by design — the sensor limitation remains; the IMU inner loop is what keeps it from mattering. This cascade is also the fallback / RECUPERANDO / CRUCERO law and the blend term in SIGUIENDO.
ERR-03 — wide-angle NoIR lens put a red cast on every frame
First seen2026-07, after the lens swap; corrected on return, 2026-08-07
Change that caused itMoved from a ~63° lens to a ~120° wide-angle lens to see far enough ahead to react to a pillar and read the corner on the same frame. The wide lens has no IR-cut filter (NoIR).
SymptomEvery frame came out heavily red-tinted. HSV masks for the floor, the orange line and the red/green pillars all broke.
Root causeWith no IR-cut filter the sensor integrates near-IR the eye doesn't see; on this sensor it lands mostly in the red channel.
FixPinned the libcamera pipeline to fixed white-balance — libcamerasrc awb-enable=false colour-gains=<1.2,1.5> — so auto-WB can't chase the cast, then re-tuned the red/green HSV ranges on the corrected image (945c2f1, 2026-08-07, and the vision.py range passes after it).
StatusResolved on the Pi 4. The wide FOV is now a net win — more track and obstacle zone per frame.
v2 update (Raspberry Pi 5)The Pi 5 has a different image processor and tuning. With fixed gains only, the frame edges showed a strong magenta ring (corners R/G ≈ 1.31–1.40 on a white sheet). Root cause: the factory lens-shading table (ALSC) is made for the stock lens and raises red at the corners. Fix: new ALSC table calibrated for our lens from 5 photos of a white sheet with the official tool (rpi-ctt), brightness part symmetrized, shipped as camera_tuning/imx219_noir_wro_pi5.json + gains <1.10,1.51>. Result: R/G and B/G = 1.00 at the center and at all corners. See ERR-29.
ERR-04 — TB6612 and motor destroyed by a reversal with no coast delay
First seen2026-08 → 09, SectionTurning MANIOBRA bring-up
SymptomWhile testing the maneuver, the code switched the motor from forward to reverse with no gap between the two. A current spike followed; one TB6612 driver and one N20 motor were lost.
Root causeSoftware, not hardware: the forward → reverse transition energised the H-bridge in the opposite direction while the motor was still spinning. Back-EMF plus shoot-through current during the flip exceeded the driver's rating (classic "plugging").
FixEvery direction change in the firmware — forward↔reverse, in MANIOBRA and everywhere else — now passes through a mandatory motor-coast phase (A1 = A2 = LOW, MANIOBRA_FRENO_MS = 300) so the motor spins down before the opposite direction is energised (9219f17).
StatusResolved. No recurrence since the coast phase went in. Risk table: "H-bridge damage from direction reversal under load".
ERR-05 — ultrasonic beam cone bounces off the corner
First seen2026-08, open-round corner tuning
SymptomThe car would sail past a corner opening — it "thought" it had not reached the end wall yet when it had actually passed the turn point some time earlier.
Root causeThe front HC-SR04's beam cone widens with distance; far from the end wall it catches the corner geometry and returns a longer bounce path, so the front distance reads larger than the true straight-ahead gap. Corner detection kept waiting.
FixThe car slows to VEL_APROX_CERRADA once the front sensor drops below FRONT_SLOWDOWN_CM (60 cm) — more time to read which side opens before it is on top of the corner. Plus EMA + a 5-sample front-channel median to reject spikes, and a multi-frame confirmation before a turn is accepted. In the Obstacle round the same read drives CRUCERO → MANIOBRA instead of a continuous arc.
Verification10 complete open-round runs from varied start positions and field configurations after these changes.
StatusResolved.
ERR-06 — the car pivoted in place instead of arcing
First seen2026-08-28, sessions ~orillas 414–416, right after the frame-rate doubled (ERR-08)
SymptomApproaching a can, the car rotated on the spot instead of driving a curve around it. The can's y in the BEV barely moved (≈ 40 mm/s) — turning, not translating. RECUPERANDO then never fired (the memory never saw the can go behind the axis) so the car dug deeper in.
Root cause(1) the obstacle steer term jumped to ±0.9 — near full lock — which pivots this chassis at cruise PWM; (2) LOOKAHEAD_MIN_PX = 60 saturated the Pure Pursuit geometry, and the adaptive look-ahead / steer-gain keyed on Euclidean distance, so a can level with the car but off to the side kept those relaxed and the car drove past the point it should have turned.
FixLOOKAHEAD_MIN_PX 60 → 78; adaptive look-ahead (100 → 78 px) and _distance_steer_gain (0.30 → 1.0) re-keyed on the longitudinal gap; on a confirmed pass the runtime calls memory.forget_color_obstacles() so the centerline un-bends and the car eases out (1daf563).
VerificationSession orillas 417: dodge steer ±0.4–0.7, the can's y advanced through the pass = arc not pivot, both cans cleared, all 12 turns completed.
StatusResolved.
ERR-07 — RECUPERANDO trigger tied to assumed linear speed
First seen2026

Parts

26
QtyValueFootprintReferences
4ULTRASONICConnector_PinHeader_2.54mm:PinHeader_1x04_P2.54mm_VerticalUS1, US2, US3, US4
20.1uFCapacitor_THT:C_Disc_D7.5mm_W2.5mm_P5.00mmC2, C4
2330Resistor_THT:R_Axial_DIN0204_L3.6mm_D1.6mm_P5.08mm_HorizontalR1, R2
1100uFCapacitor_THT:CP_Radial_D5.0mm_P2.00mmC3
1470uFCapacitor_THT:CP_Radial_D5.0mm_P2.00mmC1
1BOB-12009Snapeda:CONV_BOB-12009U3
1ESP32-DEVKITC-32DESP32-DEVKITC-32D:ESP32-DEVKITC-32DU1
1EXEC_PRGMButton_Switch_THT:SW_PUSH_6mmSW1
1LOGOLogoCREEA:LogoCREEAG***
1LOGOLogoFoxR_2:LogoFoxR_2G***
1MOTORTerminalBlock_Phoenix:TerminalBlock_Phoenix_PT-1,5-2-5.0-H_1x02_P5.00mm_HorizontalJ5
1MPU6050usini_sensors:module_mpu6050U4
1PWREasyEDA:SW-TH_L22.2-W15.0-P7.00_KCD1-2P-PSW2
1PWRLED_THT:LED_D3.0mmPWR
1READYLED_THT:LED_D3.0mmREADY
1ROB-14450Snapeda:MODULE_ROB-14450U2
1SERVOConnector_PinHeader_2.54mm:PinHeader_1x03_P2.54mm_VerticalJ4
1TO_PIConnector_PinHeader_2.54mm:PinHeader_1x06_P2.54mm_VerticalTO_PI
1V1Libreria_mia:Mini560MINI560
1VCCTerminalBlock_Phoenix:TerminalBlock_Phoenix_PT-1,5-2-5.0-H_1x02_P5.00mm_HorizontalJ1

The 25 most common of 26 parts.

More from Nakashima26/WRO_FE_2026_FoxRobotics

2
  • 2 layers117.5 × 50.6 mmWRO RevB 2, the printed circuit board in 3D

    WRO RevB 2

    Nakashima26/WRO_FE_2026_FoxRobotics

    CETYS Mexicali WRO2026 FoxRobotics Team

    26 parts1MIT
  • 2 layers117.5 × 50.6 mmWRO RevB 1, the printed circuit board in 3D

    WRO RevB 1

    Nakashima26/WRO_FE_2026_FoxRobotics

    CETYS Mexicali WRO2026 FoxRobotics Team

    23 parts1MIT

Similar boards

  • 2 layers85.6 × 26 mmGame boy pico link board, the printed circuit board in 3D

    Game boy pico link board

    agtbaskara/game-boy-pico-link-board

    An Open-Source USB to Gameboy Link Cable Adapter for Raspberry Pi Pico

    6 parts51MIT
  • 2 layers70 × 90 mmShawazu gb dumper, the printed circuit board in 3D

    Shawazu gb dumper

    tihmstar/shawazu-gb-dumper-hardware

    Shawazu GB Dumper hardware

    17 parts14
  • 2 layers76.7 × 35.1 mmWeather station, the printed circuit board in 3D

    Weather station

    VincentKobz/diy-weather-station

    The goal is to build from scratch a small intelligent weather station that can be connected to IOT networks.

    14 parts2MIT
  • 2 layers39.5 × 30.5 mmVC Adapter, the printed circuit board in 3D

    VC Adapter

    Gr3nSkyDragon/VC-Adapter

    Firmware and PCB for GB to 3DS communication

    10 parts1GPL-3.0
  • 2 layers60 × 30 mmGPIO circuit, the printed circuit board in 3D

    GPIO circuit

    JhouLab/Pi5WebcamRecorder

    Records MV4 AVI video files from up to 4 simultaneous USB webcams on Raspberry Pi 5

    7 parts1

Questions

How big is the WRO RevA PCB?

It measures 87.2 × 93.9 mm and has 2 copper layers, 1.6 mm thick.

What parts does the WRO RevA use?

26 parts, built around the BOB-12009 and ROB-14450. The full list of its parts is on this page, with links to each part's symbol and footprint where PCBKit's library has them.

Where can I download the WRO RevA KiCad files?

From the Nakashima26/WRO_FE_2026_FoxRobotics repository on GitHub, at the commit this page was made from: the board is electrical/WRO_RevA/WRO_RevA.kicad_pcb and its schematic electrical/WRO_RevA/WRO_RevA.kicad_sch. PCBKit opens the board in the browser, with nothing to install.

Can I use the WRO RevA design in my own project?

Its repository publishes it under the MIT licence: you may reuse it on that licence's terms (keep the author's notice, and for a copyleft licence share your changes alike).