🧭 Autonomous Robot
The Track 1 rover gets phone control, a sense of position, and a real control brain. You’ll set up Wi-Fi and BLE, measure rotation and distance with an IMU and encoders, master PID, run several tasks at once, log everything in graphs, and finish with a PID line follower that you tune by looking at the data.
How to read this map: the first three steps (blue) give the robot remote control, an idea of where it is, and the ability to reach a target without oscillating. The next two (cyan) organize the code and show what happens inside. The final one, highlighted, brings everything together in the line follower. Already know Wi-Fi? Start with 2.2.
🏁 What you’ll build in this track
The same rover from Track 1, now with wheel encoders, an IMU, and a line sensor bar underneath. Along the way, you’ll build a joystick controller in your phone’s browser, a tilt meter, the robot’s position in x, y, and θ, two wheels that move at the same speed, a data logger on a microSD card, and a live dashboard. At the end, the robot follows a black line through sharp turns and intersections, racing against the clock.
- ✓Complete ESP32 code using the 3.x API
- ✓PID you can test on a simulated motor
- ✓Safe stop when the signal drops
- ✓A direct foundation for micro-ROS in Track 4
💡 Before you start
You need the rover from 1.6 up and running and know how to use the Serial Monitor. PID (2.3) and non-blocking code (2.4) run in Wokwi; the IMU and encoders require the kit components listed below.
Track map
📱 Phone control: Wi-Fi and BLE
Joystick in the browser, stop if the signal drops
🧭 IMU and encoders: know where you are
How far you turned, how far you traveled, where you are
🎯 PID control in practice
Reach the target and stay there
🧵 Several tasks at once
Goodbye delay(), hello FreeRTOS
📈 Telemetry and data logging
See inside the robot as it moves
🏁 Project: PID line follower
Sharp turns against the clock
Detailed content
📱 Phone control: Wi-Fi and BLE
Wi-Fi in station and access point modes, a page with buttons, low-latency WebSocket, BLE with a generic app, a command watchdog, and a browser joystick for driving the rover.
The two ways the ESP32 can use Wi-Fi: join your home network or create its own, with a sketch that tries one and falls back to the other.
All wireless control and telemetry start here; choosing the right mode prevents a robot that won’t connect at a science fair.
STA · AP · IP address · 2.4 GHz.
The 3.x WebServer library serving a page with five buttons that send commands to the robot.
Any phone becomes a controller, with no app to install, and the same server can later adjust parameters.
Route · GET request · handleClient · fetch.
A channel that stays open between the browser and the ESP32, carrying short commands in both directions.
A joystick and continuous telemetry need low latency; HTTP opens and closes a connection for every command.
Latency · open channel · two-way · WebSockets library.
Low-energy Bluetooth with the BLE library built into the esp32 package: one service, one characteristic, and a generic app.
Works without any network and uses the same pattern as wireless controllers and sensors.
Service · characteristic · UUID · advertising.
Password on the robot’s network and a command watchdog: if no new message arrives for 300 ms, the robot stops on its own.
The signal drops; a robot that keeps going with its last “forward” command will crash. Fail-safe behavior is a rule for every real robot.
Watchdog · timeout · fail-safe · maximum speed on the robot.
Complete sketch: access point, joystick page, WebSocket, differential mixing, and watchdog, driving the real rover.
Every autonomous robot needs this manual mode for testing and recovery.
Differential mixing · pointer events · raw string · 10 sends per second.
🧭 IMU and encoders: know where you are
Accelerometer and gyroscope, the MPU-6050 read directly through its registers, the complementary filter, quadrature encoders, and odometry in x, y, and θ, including the errors that accumulate.
The chip that senses gravity and rotation on three axes, and the strength and weakness of each sensor.
Turning exactly 90°, sensing a ramp, and detecting a fall all depend on it.
g · °/s · integration · drift · MPU-6050 vs. ICM-20948.
Four wires and a sketch that wakes the sensor and reads 14 bytes of acceleration and gyroscope data, with no extra library.
The same approach works for almost any I2C sensor you use later.
Register · address 0x68 · burst read · unit conversion.
Combine the gyroscope (fast, drifts) and accelerometer (slow, noisy) to get a stable tilt reading, with three curves in the Serial Plotter.
This is the simplest form of sensor fusion and a first step toward the Kalman filter.
atan2 · gyroscope offset · α = 0,98 · fixed dt.
A disk or magnet that generates pulses; two quadrature channels give you direction; an interrupt counts every pulse.
The wheel’s actual speed is the PID input and the basis for odometry.
Pulses per revolution · quadrature · ISR with IRAM_ATTR · volatile.
Five lines of calculations add up how far each wheel has traveled and turn that into position and direction.
Returning to base and moving to a point require knowing where you are; this is what micro-ROS publishes in Track 4.
Pose · meters per pulse · distance between wheels · radians.
Why the estimated position drifts from the real one, and a four-step calibration that reduces the error.
Shows when odometry is enough and when the robot needs a line, camera, or LiDAR to correct itself.
Accumulated error · systematic error · slippage · external reference.
🎯 PID control in practice
Why on/off control oscillates, the role of P, I, and D, a complete PID tested on a simulated motor, a method for tuning, anti-windup, and keeping two wheels at the same speed.
The back-and-forth motion of a system that only knows “all or nothing,” and the idea of correcting in proportion to the error.
This is the problem PID solves in cars, drones, 3D printers, and robot arms.
Target · measurement · error · closed loop.
Proportional steering, correcting for constant wind, and braking before you overshoot: the three letters explained with an analogy and three curves.
Once you understand what each gain does, you can tune by reading the graph instead of guessing.
Kp · Ki · Kd · overshoot · steady-state error.
A complete PID at 100 Hz controlling a simulated motor, with gains adjustable through the Serial Monitor, running in Wokwi.
This is the structure you can reuse for the line follower and every control system you build later.
Fixed period · micros() · simulated plant · Serial Plotter.
The P → I → D order for manual tuning, and the Ziegler-Nichols table based on the critical gain.
A poorly tuned PID oscillates and heats up the motor; with a method, a few tests are enough.
Ku · Tu · one gain at a time · test on the floor.
The three pitfalls of real-world PID and the four lines of code that fix them.
This is the difference between a PID that works in simulation and one that works on the robot.
Saturation · anti-windup · derivative of the measurement · low-pass filter.
One PI controller per wheel, the same RPM target, and each reading its own encoder: the rover drives straight.
A stable foundation for the line follower and for ROS 2 /cmd_vel.
One PID per wheel · measured RPM · PI is enough · reset the integral when stopping.
🧵 Several tasks at once
Why delay() stops the robot, non-blocking tasks with millis(), state machines, FreeRTOS tasks on both cores, queues and semaphores, and code organized into files and classes.
What happens to sensors, PID, and communication while the program is paused in a delay().
A robot that is “blind” for half a second hits an obstacle before it notices it.
Blocking code · response time · main loop.
Give each task its own clock: read a sensor every 20 ms, blink an LED every 500 ms, and send telemetry every 100 ms.
This is the simplest way to do several things “at the same time” in a single loop.
Periodic task · millis() rollover · cooperative scheduler.
Draw the states, events, and transitions before writing the code, with entry and exit actions.
Complex behavior without nested if statements; easy to test and change.
State · event · transition · enum class.
The real-time operating system that already runs inside the ESP32: create tasks with priorities and choose which core each one runs on.
Motor control stays on schedule even while Wi-Fi and telemetry are using the processor.
Task · priority · core · vTaskDelayUntil.
How one task safely passes data to another without both changing the same variable at the same time.
Prevents the hardest errors to track down: corrupted values that show up once an hour.
Queue · mutex · semaphore · race condition.
Separate motors, sensors, and control into .h/.cpp tabs and small classes within the sketch.
The line follower from 2.6 and the robot from Track 3 can grow without turning into a thousand-line file.
Class · header file (.h) · single responsibility · reusability.
📈 Telemetry and data logging
What to measure and how often, a live graph in the Serial Plotter, logging to a CSV file on the microSD card, MQTT over the network, a dashboard in a browser or in Node-RED/Grafana, and analysis in Python.
Choose the variables that explain the robot’s behavior and the right rate for each one.
Measuring everything overwhelms the processor; measuring too little doesn’t explain the failure.
Sampling rate · timestamp · state variable.
The "name:value" format that Arduino IDE 2 turns into curves, with several variables displayed together.
It’s the fastest tool for tuning PID and finding noise.
Label · scale · time window.
Record data in a comma-separated text file, without a cable, while the robot moves for real.
A robot far from the computer still needs to report what happened.
SPI · CSV file · flush · FAT32 card.
The lightweight protocol for publishing and subscribing to messages by topic, with a broker on the PC or Raspberry Pi.
Multiple robots and dashboards communicate over the same channel; ROS 2 expands on this idea.
Broker · topic · publish · subscribe.
View telemetry in real time: a page served by the ESP32 itself or a dashboard built in Node-RED or Grafana.
Seeing the robot "from the inside" helps you debug and present the project.
Dashboard · time series · WebSocket · indicator.
Open the CSV on your computer, calculate averages and errors, and plot before-and-after results.
Use the numbers to decide whether the adjustment improved the robot, not just your impression.
pandas · DataFrame · matplotlib · before-and-after comparison.
🏁 Project: PID line follower
Track and sensor bar, line error calculated with a weighted average, steering PID applied to the base speed, automatic calibration, telemetry-based tuning, and challenges against the clock.
Build a track with black electrical tape and position the 5-sensor IR bar at the right height.
Sensor height and spacing determine half of a line follower’s performance.
TCRT5000 / QTR · sensor height · track contrast.
Turn five readings into a single number: the line’s position relative to the center of the robot.
A continuous error, rather than "left/right," is what makes a smooth PID possible.
Weighted average · line position · line lost.
Add the PID correction to one wheel and subtract it from the other, on top of a base speed.
This is the architecture used by almost every competition line follower.
Base speed · correction · per-wheel saturation.
The robot turns over the line during the first few seconds and learns the minimum and maximum for each sensor.
Ambient light and track conditions vary from place to place; calibrating on the spot saves you from rewriting the code.
Minimum and maximum · normalization · EEPROM/Preferences.
Record the line error for one lap, change one gain, record it again, and compare the graphs.
Turn "it seems better" into "the average error dropped by half."
Average error · lap time · one adjustment at a time.
More difficult tracks, recognizing intersections and a lost line, and timing the lap.
Prepares you for competitions such as OBR and for the vision-based robot in Track 3.
Adaptive speed · last-error memory · timed lap.
📌 Track pin map
All of Track 2 uses the same map. It differs slightly from the Track 1 rover: the right motor moves from pins 33/32/4 to 14/16/17, and the driver’s STBY is connected directly to 3V3. This frees up ADC1 pins for the line sensors and pins 18/19 for the encoders or microSD.
| Part | ESP32 pin | Modules |
|---|---|---|
| Left motor (TB6612FNG) | PWMA 25, AIN1 26, AIN2 27 | 2.1, 2.3, 2.4, 2.6 |
| Right motor | PWMB 14, BIN1 16, BIN2 17 | 2.1, 2.3, 2.4, 2.6 |
| Driver STBY | 3V3 | all |
| Encoders | left 18/19, right 34/35 | 2.2, 2.3 |
| HC-SR04 | TRIG 13, ECHO 4 (divider to 3.3 V) | 2.4 |
| microSD | CS 5, SCK 18, MISO 19, MOSI 23 | 2.5, 2.6 |
| Line sensors | 36, 39, 34, 35, 32 (ADC1 only) | 2.6 |
✗ What can’t be connected at the same time
The encoders and microSD share pins 18 and 19, and the right encoder uses 34/35, which are also line sensor pins. So each project connects only what it uses: the PID project in 2.3 uses encoders without microSD; the line follower in 2.6 uses sensors and microSD without encoders.
🧰 Trail kit
Parts to add to the Track 1 rover. Approximate range of R$ 150 a R$ 350 for the extra set (Oct/2026; check before buying: prices vary by store, shipping, and exchange rate).
MPU-6050 module (GY-521), the cheapest and best-documented option. Alternative with a compass: ICM-20948 (9-axis), more expensive.
Pair of N20 motors with magnetic encoders (two channels) and wheels, or the T1 TT motors with encoder disks and optical sensors.
Bar with 5 infrared sensors (TCRT5000) or a QTR bar, with analog output, for the line follower in 2.6.
microSD card reader module (SPI, 3.3 V) and an 8 to 32 GB card formatted as FAT32.
SSD1306 OLED display (I2C, 0.96") to show status, gains, and lap time on the robot itself.
19 mm black electrical tape on white poster board, light MDF, or a smooth floor.
✓ Worth it
Two-channel encoders (they tell you the direction of rotation) and firm rubber wheels, which slip less and make odometry more reliable.
✗ Don’t buy these for this trail
Single-bit digital line sensors (they only say “line: yes/no”) and 5 V IMU modules without a regulator.