Reading Time: 20 minutes

Combining laser distance measurement, numerical differentiation, motion prediction and PID motor control to create a system that reacts to movement before it reaches its next measured position.

Introduction

In the previous three articles, we explored how an ESP32 microcontroller could bring mathematical differentiation into the physical world.

In Part 1, we introduced the underlying mathematics and examined how differentiation could be used for measurement and control.

In Part 2, we constructed a laser-based motion analyser that calculated position, velocity, acceleration and jerk from successive distance measurements.

In Part 3, we developed a closed-loop motor controller using a rotary encoder and PID feedback.

Now we are going to combine those two systems.

Our objective is to create a device capable of measuring the movement of an object, estimating where it is likely to be a short time later, and automatically adjusting a motor-driven pointer to follow it.

This introduces an important concept in engineering: predictive control.

Rather than responding exclusively to the latest measurement, the ESP32 will use information about the object's current velocity to estimate its near-future position.

The motor controller will then attempt to follow that predicted position.

We will also be able to switch prediction off and compare its performance against conventional position tracking.

By the end of this project, we will have a practical experimental platform combining sensing, signal processing, mathematical modelling, embedded programming and feedback control.


1. What Are We Building?

Our system will measure how far a target is from a laser distance sensor.

A motor-driven pointer will represent that distance on a semicircular scale.

As the target moves closer or farther away, the pointer will rotate.

For example:

Target distancePointer angle
200 mm0°
375 mm45°
550 mm90°
725 mm135°
900 mm180°

This mapping allows us to convert linear movement into rotational movement.

The sensor measures the target's position along one axis, while the motor provides a visual indication of that position.

Importantly, this is one-dimensional motion tracking. A single VL53L0X sensor cannot determine whether an object has moved left or right. Building a true two-axis tracking system would require additional sensing and actuation.

What makes the system predictive?

Suppose a target is currently 500 mm from the sensor.

The ESP32 calculates that it is moving away at 200 mm/s.

If we assume this velocity remains constant for the next 0.15 seconds, the predicted position becomes:

500 + (200 × 0.15) = 530 mm.

Instead of commanding the motor to represent 500 mm, we could command it to represent 530 mm.

The intention is to compensate for delays in sensing, filtering and mechanical response.

Prediction will not always improve the result. It can actually make tracking worse if the target suddenly changes direction or if the velocity estimate is noisy.

That is why comparing predictive and non-predictive operation will form a major part of this experiment.


2. Hardware Requirements

We can reuse most of the components from Parts 2 and 3.

This time, we will connect both subsystems to a single ESP32.

ComponentQuantityPurpose
ESP32 DevKit, original dual-core ESP321Processing and control
VL53L0X distance sensor breakout1Target measurement
Pololu 50:1 MP 6V gearmotor with encoder, #51341Controlled pointer movement
Pololu TB6612FNG carrier, #7131Motor power control
Matching six-pin encoder cable1Motor and encoder wiring
Regulated 6V motor supply1Motor power
Motor supply isolation switch1Physical power disconnect
Normally open pushbutton1Software stop input
Breadboard and suitable wiringAs requiredElectrical connections
Small pointer and motor bracket1 eachMechanical display
Flat target and linear guide1 eachRepeatable experiments
USB power source1ESP32 power

The motor's nominal voltage is 6V, its gearbox ratio is approximately 51.45:1, and its theoretical stall current is about 0.67A.

The TB6612FNG carrier supports approximately 1A continuous per channel under appropriate thermal conditions, so it is suitable for this particular small motor and an appropriately limited supply.

These component choices are supported by the manufacturers' published specifications.

Constructing the physical mechanism

For our first build, the motor should drive a very lightweight pointer.

The pointer could be made from thin plastic or another low-mass material.

Mount the pointer in front of a printed 0–180-degree scale.

Leave sufficient clearance for it to rotate without contacting the surrounding structure.

We will use the shaft's position at power-up as the initial zero-degree reference.

This is only a relative reference. A proper home switch would be necessary for repeatable absolute positioning after power cycles.

The distance sensor should face a movable, flat target.

A simple hand-operated linear slide is sufficient for early experiments.

For repeatable testing, a motorised linear carriage would be a useful future addition.


3. The Complete System Architecture

Our design contains two feedback-related processes.

The first estimates how the target is moving.

The second controls the motor.

Measurement and prediction

The VL53L0X provides distance measurements.

The ESP32 filters those measurements to reduce noise.

Numerical differentiation estimates the target's velocity.

The software then predicts the target's position a short time into the future.

Position control

The predicted distance is converted into a required motor angle.

A motion-profile generator limits the rate at which the requested motor position changes.

The PID controller compares that reference with the motor's actual measured position.

Using encoder feedback, the ESP32 adjusts motor power to reduce the error.

The process is:

                  MOVING TARGET
                        |
                        v
               +-----------------+
               | VL53L0X Sensor  |
               +-----------------+
                        |
                  Raw Distance
                        |
                        v
                Position Filter
                        |
                        v
              Numerical Derivative
                        |
                 Target Velocity
                        |
                        v
               Motion Prediction
                        |
                Predicted Distance
                        |
                        v
                Distance-to-Angle
                    Conversion
                        |
                        v
                Motion Profile
                        |
                        v
                 PID Controller
                        |
                        v
                  Motor Driver
                        |
                        v
                  DC Gearmotor
                        |
                        v
                 Rotary Encoder
                        |
                        +-------> Feedback

This architecture demonstrates how measured data can be converted into a control decision.

One important design consideration is that the sensor and motor controller operate at different update rates.

We will aim for approximately 20 distance measurements per second and 50 motor-control updates per second.

These are nominal rates, not guaranteed hard real-time deadlines.


4. Connecting the Hardware

The distance sensor uses the ESP32's I²C interface.

The motor driver uses digital direction signals and PWM.

The encoder uses two digital input pins.

Distance sensor connections

VL53L0XESP32
VIN3.3V
GNDGND
SDAGPIO 21
SCLGPIO 22

Use a breakout board confirmed to support 3.3V operation and 3.3V I²C logic.

Motor-driver connections

TB6612FNGConnection
VCCESP32 3.3V
GNDCommon ground
VMOTRegulated 6V motor supply
AIN1GPIO 18
AIN2GPIO 19
PWMAGPIO 25
STBYGPIO 23
AO1Motor terminal M1
AO2Motor terminal M2

Encoder connections

Using the specified Pololu colour-coded cable:

Encoder wireESP32 connection
Green, GNDGND
White, channel BGPIO 33
Yellow, channel AGPIO 32
Blue, encoder supply3.3V
Black, motor M2Driver AO2
Red, motor M1Driver AO1

The software stop button connects between GPIO 27 and ground.

Connect the ESP32 ground and motor-supply negative together.

Do not connect the 6V motor supply directly to the ESP32's 3.3V pin.

The motor driver should have suitable decoupling near its supply terminals. Keep the encoder wiring away from motor-current wiring where practical.

The unused TB6612FNG channel should have its control inputs held in defined inactive states, with its outputs left disconnected.

Safety: The motor should be powered through a current-limited supply and an accessible physical isolation switch. The GPIO stop button and browser stop command are not safety-rated emergency stops.


5. Understanding the Prediction Mathematics

The first stage of our calculations is identical to the motion analyser developed in Part 2.

The sensor measures the position of the target.

Differentiation estimates velocity:

v = dx/dt

We calculate this using successive measurements:

v ≈ (x₂ − x₁) / Δt

Once we know position and velocity, we can estimate future position.

For a constant-velocity model:

x(t + T) ≈ x(t) + v(t)T

Where:

  • x(t) is the present position.
  • v(t) is the estimated velocity.
  • T is the prediction horizon.
  • x(t + T) is the predicted future position.

For example, assume:

Current position = 0.45 m

Estimated velocity = 0.30 m/s

Prediction horizon = 0.12 seconds.

Then:

Predicted position = 0.45 + (0.30 × 0.12)

Predicted position = 0.486 m

The controller therefore operates on an estimate of where the object may be 120 milliseconds into the future.

Why use 120 milliseconds?

We need a starting value for our experiments.

A short horizon may help compensate for some measurement and control delays.

However, increasing the horizon also increases the risk of prediction error.

For example, a prediction based on constant velocity will be wrong whenever the target changes speed.

We will begin with a 120 ms horizon and test shorter and longer values.

Could we include acceleration?

Yes.

A constant-acceleration prediction would be:

x(t + T) ≈ x(t) + v(t)T + ½a(t)T²

This could provide better predictions when acceleration can be estimated reliably.

However, our previous experiments demonstrated that acceleration estimates can be very sensitive to measurement noise.

For the initial build, we will use velocity-only prediction.

This keeps the model simple and makes experimental results easier to interpret.


6. Converting Distance into Motor Angle

The next step is to translate the sensor measurement into a motor position.

Our measurement scale is:

Minimum mapped distance = 200 mm

Maximum mapped distance = 900 mm

Motor angle range = 0–180 degrees.

The conversion is:

Angle = 180 × (Distance − 200) / 700

The result is constrained to the 0–180-degree range.

For example, if the predicted distance is 550 mm:

Angle = 180 × (550 − 200) / 700

Angle = 90 degrees

In our program, the conversion is:

float distanceToAngle(float distanceM) {
  float ratio =
    (distanceM - 0.20f) / 0.70f;

  ratio = constrain(ratio, 0.0f, 1.0f);

  return ratio * 180.0f;
}

The actual sensor-validity window will be slightly wider than the mapped range.

This prevents very small boundary movements from immediately causing a measurement fault.

The mechanical pointer will only be commanded to positions within 0–180 degrees, although the software will also monitor for excessive actual shaft movement.

A physical home reference is recommended before this design is used in any more demanding application.


7. Integrating the Firmware

We will now combine the sensing and motor-control functions.

Rather than using one loop for every task, we will use separate FreeRTOS tasks.

The sensor task will collect readings and calculate the predicted position.

The motor task will run its control loop independently.

The main Arduino loop will handle the web dashboard.

Shared measurement data will be protected when accessed by different tasks.

This is a development reference implementation for the original dual-core ESP32 using Arduino-ESP32 3.x-compatible APIs.

It assumes that the motor polarity, encoder direction and basic PID operation have already been verified using the tests from Part 3.

Complete integrated ESP32 sketch

Create a sketch named ESP32_Predictive_Tracker and enter the following code.

#include <Arduino.h>
#include <Wire.h>
#include <WiFi.h>
#include <WebServer.h>
#include <Adafruit_VL53L0X.h>
#include <math.h>

// Pins
constexpr int IN1 = 18;
constexpr int IN2 = 19;
constexpr int PWM_PIN = 25;
constexpr int STBY = 23;
constexpr int ENC_A = 32;
constexpr int ENC_B = 33;
constexpr int STOP_PIN = 27;

// Sensor settings
constexpr float NEAR_M = 0.20f;
constexpr float FAR_M = 0.90f;
constexpr float LOOKAHEAD_S = 0.12f;
constexpr float POS_ALPHA = 0.35f;
constexpr float VEL_ALPHA = 0.25f;

// Motor settings
constexpr float COUNTS_PER_REV =
    12.0f * 51.45f;

// Change only after motor direction testing
constexpr float ENCODER_SIGN = 1.0f;

constexpr float MAX_REF_SPEED = 90.0f;
constexpr float MAX_REF_ACCEL = 180.0f;

// Initial gains: require hardware tuning
constexpr float KP = 3.0f;
constexpr float KI = 0.0f;
constexpr float KD = 0.30f;

constexpr int MAX_PWM = 130;

Adafruit_VL53L0X tof;
WebServer server(80);

// Shared state
struct State {
  bool sensorValid = false;
  bool armed = false;
  bool prediction = false;
  int fault = 0;

  uint32_t lastGoodMs = 0;

  float rawM = 0;
  float filteredM = 0;
  float targetVelocity = 0;
  float predictedM = 0;

  float targetDeg = 0;
  float referenceDeg = 0;
  float actualDeg = 0;
  float motorVelocity = 0;
  float errorDeg = 0;

  int pwm = 0;
};

State shared;

portMUX_TYPE dataMux =
    portMUX_INITIALIZER_UNLOCKED;

portMUX_TYPE encoderMux =
    portMUX_INITIALIZER_UNLOCKED;

volatile int32_t encoderCount = 0;
volatile uint8_t lastAB = 0;

// Quadrature transition table
const int8_t QTABLE[16] = {
   0, -1,  1,  0,
   1,  0,  0, -1,
  -1,  0,  0,  1,
   0,  1, -1,  0
};

void IRAM_ATTR encoderISR() {
  portENTER_CRITICAL_ISR(&encoderMux);

  uint8_t ab =
    (digitalRead(ENC_A) << 1) |
     digitalRead(ENC_B);

  encoderCount +=
    QTABLE[(lastAB << 2) | ab];

  lastAB = ab;

  portEXIT_CRITICAL_ISR(&encoderMux);
}

int32_t readEncoder() {
  portENTER_CRITICAL(&encoderMux);
  int32_t n = encoderCount;
  portEXIT_CRITICAL(&encoderMux);
  return n;
}

State snapshot() {
  portENTER_CRITICAL(&dataMux);
  State s = shared;
  portEXIT_CRITICAL(&dataMux);
  return s;
}

void setFault(int faultCode) {
  portENTER_CRITICAL(&dataMux);

  if (shared.fault == 0)
    shared.fault = faultCode;

  shared.armed = false;

  portEXIT_CRITICAL(&dataMux);
}

float distanceToAngle(float metres) {
  float ratio =
    (metres - NEAR_M) /
    (FAR_M - NEAR_M);

  return 180.0f *
    constrain(ratio, 0.0f, 1.0f);
}

void motorOff() {
  ledcWrite(PWM_PIN, 0);
  digitalWrite(STBY, LOW);
}

void driveMotor(int command) {
  command =
    constrain(command, -MAX_PWM, MAX_PWM);

  ledcWrite(PWM_PIN, 0);

  if (command == 0) {
    digitalWrite(STBY, LOW);
    return;
  }

  digitalWrite(
    IN1, command > 0 ? HIGH : LOW
  );

  digitalWrite(
    IN2, command > 0 ? LOW : HIGH
  );

  digitalWrite(STBY, HIGH);

  ledcWrite(PWM_PIN, abs(command));
}

// Sensor task: nominally 20 Hz
void sensorTask(void* parameter) {
  TickType_t wake = xTaskGetTickCount();

  bool havePrevious = false;
  float x = 0;
  float v = 0;
  uint32_t previousUs = 0;

  while (true) {
    vTaskDelayUntil(
      &wake, pdMS_TO_TICKS(50)
    );

    VL53L0X_RangingMeasurementData_t m;

    VL53L0X_Error result =
      tof.rangingTest(&m, false);

    uint32_t nowUs = micros();

    bool ok =
      result == VL53L0X_ERROR_NONE &&
      m.RangeStatus == 0 &&
      m.RangeMilliMeter >= 150 &&
      m.RangeMilliMeter <= 1000;

    if (!ok) {
      havePrevious = false;

      portENTER_CRITICAL(&dataMux);
      shared.sensorValid = false;
      portEXIT_CRITICAL(&dataMux);

      continue;
    }

    float raw =
      m.RangeMilliMeter / 1000.0f;

    if (!havePrevious) {
      x = raw;
      v = 0;
      havePrevious = true;
    } else {
      float dt =
        float(uint32_t(
          nowUs - previousUs
        )) / 1000000.0f;

      if (dt > 0 && dt < 0.25f) {
        float oldX = x;

        x =
          POS_ALPHA * raw +
          (1.0f - POS_ALPHA) * x;

        float measuredV =
          (x - oldX) / dt;

        v =
          VEL_ALPHA * measuredV +
          (1.0f - VEL_ALPHA) * v;
      } else {
        x = raw;
        v = 0;
      }
    }

    previousUs = nowUs;

    float predicted =
      x + v * LOOKAHEAD_S;

    predicted =
      constrain(predicted,
                NEAR_M, FAR_M);

    portENTER_CRITICAL(&dataMux);

    shared.rawM = raw;
    shared.filteredM = x;
    shared.targetVelocity = v;
    shared.predictedM = predicted;
    shared.lastGoodMs = millis();
    shared.sensorValid = true;

    portEXIT_CRITICAL(&dataMux);
  }
}

// Motor task: nominally 50 Hz
void motorTask(void* parameter) {
  TickType_t wake = xTaskGetTickCount();

  uint32_t previousUs = micros();

  float previousAngle = 0;
  float motorVelocity = 0;
  float reference = 0;
  float referenceVelocity = 0;
  float integral = 0;

  int32_t progressCount = 0;
  uint32_t lastProgressMs = millis();

  while (true) {
    vTaskDelayUntil(
      &wake, pdMS_TO_TICKS(20)
    );

    uint32_t nowUs = micros();

    float dt =
      float(uint32_t(
        nowUs - previousUs
      )) / 1000000.0f;

    previousUs = nowUs;

    if (dt < 0.005f || dt > 0.10f) {
      setFault(4);
      dt = 0.02f;
    }

    int32_t count = readEncoder();

    float angle =
      ENCODER_SIGN *
      float(count) *
      360.0f / COUNTS_PER_REV;

    float instantVelocity =
      (angle - previousAngle) / dt;

    previousAngle = angle;

    motorVelocity =
      0.25f * instantVelocity +
      0.75f * motorVelocity;

    State s = snapshot();

    if (digitalRead(STOP_PIN) == LOW)
      setFault(1);

    if (angle < -10 || angle > 190)
      setFault(2);

    if (s.armed &&
        millis() - s.lastGoodMs > 350)
      setFault(3);

    s = snapshot();

    bool fresh =
      s.sensorValid &&
      (millis() - s.lastGoodMs < 250);

    float goal = s.targetDeg;
    float error = 0;
    int command = 0;

    if (!s.armed ||
        s.fault != 0 ||
        !fresh) {

      motorOff();

      reference = angle;
      referenceVelocity = 0;
      integral = 0;

      progressCount = count;
      lastProgressMs = millis();

    } else {

      float chosenDistance =
        s.prediction ?
        s.predictedM : s.filteredM;

      goal = distanceToAngle(
        chosenDistance
      );

      float remaining =
        goal - reference;

      float direction =
        remaining >= 0 ? 1.0f : -1.0f;

      float stopSpeed =
        sqrtf(
          2.0f * MAX_REF_ACCEL *
          fabsf(remaining)
        );

      float wantedSpeed =
        direction *
        fminf(MAX_REF_SPEED, stopSpeed);

      referenceVelocity += constrain(
        wantedSpeed - referenceVelocity,
        -MAX_REF_ACCEL * dt,
         MAX_REF_ACCEL * dt
      );

      float nextReference =
        reference +
        referenceVelocity * dt;

      if ((remaining >= 0 &&
           nextReference > goal) ||
          (remaining < 0 &&
           nextReference < goal)) {

        reference = goal;
        referenceVelocity = 0;

      } else {
        reference = nextReference;
      }

      error = reference - angle;

      // Integral term, initially disabled
      integral = constrain(
        integral + error * dt,
        -60.0f,
         60.0f
      );

      float output =
        KP * error +
        KI * integral -
        KD * motorVelocity;

      command = int(roundf(constrain(
        output,
        -float(MAX_PWM),
         float(MAX_PWM)
      )));

      if (fabsf(error) < 1.0f &&
          fabsf(motorVelocity) < 3.0f)
        command = 0;

      // Basic encoder-progress check
      if (abs(command) >= 95) {
        if (labs(long(count) -
                 long(progressCount)) >= 3) {

          progressCount = count;
          lastProgressMs = millis();

        } else if (
          millis() - lastProgressMs > 800
        ) {
          setFault(5);
          command = 0;
        }
      } else {
        progressCount = count;
        lastProgressMs = millis();
      }

      // Recheck state before driving
      State latest = snapshot();

      if (latest.armed &&
          latest.fault == 0 &&
          digitalRead(STOP_PIN) == HIGH) {

        driveMotor(command);

      } else {
        command = 0;
        motorOff();
      }
    }

    portENTER_CRITICAL(&dataMux);

    shared.targetDeg = goal;
    shared.referenceDeg = reference;
    shared.actualDeg = angle;
    shared.motorVelocity = motorVelocity;
    shared.errorDeg = error;
    shared.pwm = command;

    portEXIT_CRITICAL(&dataMux);
  }
}

// Standalone dashboard
const char PAGE[] PROGMEM = R"HTML(
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport"
 content="width=device-width,initial-scale=1">
<title>ESP32 Predictive Tracker</title>
<style>
body{
  font-family:Arial,sans-serif;
  background:#f2f5f8;
  color:#223;
  margin:0;
}
main{
  max-width:900px;
  margin:auto;
  padding:20px;
}
.card{
  background:white;
  border-radius:12px;
  padding:18px;
  margin-bottom:15px;
}
.grid{
  display:grid;
  grid-template-columns:
  repeat(auto-fit,minmax(140px,1fr));
  gap:10px;
}
.metric{
  background:#f1f4f7;
  padding:12px;
  border-radius:8px;
}
.metric strong{
  display:block;
  font-size:24px;
  margin-top:8px;
}
button{
  padding:12px 16px;
  border:0;
  border-radius:8px;
  background:#245ac0;
  color:white;
  margin:4px;
  cursor:pointer;
}
.stop{background:#b82e35}
canvas{
  display:block;
  width:100%;
  height:220px;
}
</style>
</head>
<body>
<main>
<h1>ESP32 Predictive Motion Tracker</h1>
<p id="status">Connecting...</p>

<div class="card">
<h3>Controls</h3>
<button onclick="send('/arm')">Enable</button>
<button onclick="send('/mode?on=0')">
Prediction OFF
</button>
<button onclick="send('/mode?on=1')">
Prediction ON
</button>
<button class="stop"
 onclick="send('/stop')">STOP</button>
<button onclick="send('/reset')">
Clear fault
</button>
</div>

<div class="card grid">
<div class="metric">Measured distance
<strong id="distance">--</strong>mm</div>
<div class="metric">Predicted distance
<strong id="forecast">--</strong>mm</div>
<div class="metric">Target velocity
<strong id="velocity">--</strong>m/s</div>
<div class="metric">Motor angle
<strong id="actual">--</strong>degrees</div>
<div class="metric">Required angle
<strong id="target">--</strong>degrees</div>
<div class="metric">PWM command
<strong id="pwm">--</strong></div>
</div>

<div class="card">
<h3>Tracking response</h3>
<p>Blue: measured target position<br>
Orange: commanded motor target<br>
Green: actual motor position</p>
<canvas id="chart"></canvas>
<button onclick="exportCSV()">Export CSV</button>
</div>
</main>

<script>
const history = [];

async function send(url) {
  const response = await fetch(url, {
    method:"POST"
  });

  if(!response.ok)
    alert(await response.text());
}

function drawChart() {
  const canvas =
    document.getElementById("chart");

  const width = canvas.clientWidth;
  const height = 220;
  const ratio = devicePixelRatio || 1;

  canvas.width = width * ratio;
  canvas.height = height * ratio;

  const ctx = canvas.getContext("2d");
  ctx.scale(ratio,ratio);

  ctx.strokeStyle="#dce1e9";

  for(let i=0;i<=4;i++){
    let y=10+i*50;
    ctx.beginPath();
    ctx.moveTo(0,y);
    ctx.lineTo(width,y);
    ctx.stroke();
  }

  const lines=[
    ["measuredAngle","#2167d4"],
    ["target","#e89719"],
    ["actual","#179e82"]
  ];

  lines.forEach(([key,color])=>{
    ctx.beginPath();
    ctx.strokeStyle=color;
    ctx.lineWidth=2;

    history.forEach((s,i)=>{
      let x=i*width/
        Math.max(1,history.length-1);

      let y=210-
        Math.max(0,Math.min(180,s[key]))
        /180*200;

      if(i===0)ctx.moveTo(x,y);
      else ctx.lineTo(x,y);
    });

    ctx.stroke();
  });
}

async function update(){
  try{
    const r=await fetch("/data",{
      cache:"no-store"
    });

    if(!r.ok)throw new Error();

    const d=await r.json();

    document.getElementById("status")
      .textContent=
      "Prediction: "+(d.prediction?
      "ON":"OFF")+
      " | Motor: "+(d.armed?
      "ENABLED":"DISABLED")+
      " | Fault: "+d.fault;

    const fields={
      distance:d.filtered*1000,
      forecast:d.predicted*1000,
      velocity:d.targetVelocity,
      actual:d.actual,
      target:d.target,
      pwm:d.pwm
    };

    for(const key in fields){
      document.getElementById(key)
        .textContent=
        Number(fields[key]).toFixed(
          key==="pwm"?0:2
        );
    }

    if(d.valid){
      history.push({
        time:Date.now(),
        ...d,
        measuredAngle:
          Math.max(0,Math.min(180,
            (d.filtered-0.20)/0.70*180
          ))
      });

      if(history.length>250)
        history.shift();

      drawChart();
    }

  }catch(e){
    document.getElementById("status")
      .textContent="Connection lost";
  }
}

function exportCSV(){
  const columns=[
    "time","filtered","predicted",
    "targetVelocity","measuredAngle",
    "target","reference","actual",
    "motorVelocity","pwm","prediction"
  ];

  const rows=[
    columns.join(","),
    ...history.map(s=>
      columns.map(k=>s[k]).join(",")
    )
  ];

  const blob=new Blob(
    [rows.join("\n")],
    {type:"text/csv"}
  );

  const url=URL.createObjectURL(blob);
  const a=document.createElement("a");
  a.href=url;
  a.download="tracking.csv";
  a.click();
  URL.revokeObjectURL(url);
}

setInterval(update,150);
update();
</script>
</body>
</html>
)HTML";

void handleData() {
  State s = snapshot();

  char json[500];

  snprintf(json,sizeof(json),
    "{\"valid\":%s,"
    "\"armed\":%s,"
    "\"prediction\":%s,"
    "\"fault\":%d,"
    "\"raw\":%.4f,"
    "\"filtered\":%.4f,"
    "\"predicted\":%.4f,"
    "\"targetVelocity\":%.4f,"
    "\"target\":%.3f,"
    "\"reference\":%.3f,"
    "\"actual\":%.3f,"
    "\"motorVelocity\":%.3f,"
    "\"pwm\":%d}",
    s.sensorValid?"true":"false",
    s.armed?"true":"false",
    s.prediction?"true":"false",
    s.fault,
    s.rawM,
    s.filteredM,
    s.predictedM,
    s.targetVelocity,
    s.targetDeg,
    s.referenceDeg,
    s.actualDeg,
    s.motorVelocity,
    s.pwm
  );

  server.send(
    200,"application/json",json
  );
}

void handleArm() {
  State s = snapshot();

  bool fresh =
    s.sensorValid &&
    millis()-s.lastGoodMs < 250;

  if(s.fault ||
     !fresh ||
     digitalRead(STOP_PIN)==LOW) {

    server.send(
      409,"text/plain",
      "Fault, stop input, or sensor invalid"
    );
    return;
  }

  portENTER_CRITICAL(&dataMux);
  shared.armed=true;
  portEXIT_CRITICAL(&dataMux);

  server.send(200,"text/plain","Enabled");
}

void handleStop() {
  portENTER_CRITICAL(&dataMux);
  shared.armed=false;
  portEXIT_CRITICAL(&dataMux);

  motorOff();

  server.send(200,"text/plain","Stopped");
}

void handleMode() {
  bool enabled =
    server.arg("on")=="1";

  portENTER_CRITICAL(&dataMux);
  shared.prediction=enabled;
  portEXIT_CRITICAL(&dataMux);

  server.send(
    200,"text/plain",
    enabled?"Prediction ON":"Prediction OFF"
  );
}

void handleReset() {
  if(digitalRead(STOP_PIN)==LOW){
    server.send(
      409,"text/plain","Release stop first"
    );
    return;
  }

  portENTER_CRITICAL(&dataMux);

  shared.fault=0;
  shared.armed=false;

  portEXIT_CRITICAL(&dataMux);

  motorOff();

  server.send(
    200,"text/plain","Fault reset"
  );
}

void setup() {
  Serial.begin(115200);

  pinMode(IN1,OUTPUT);
  pinMode(IN2,OUTPUT);
  pinMode(STBY,OUTPUT);
  pinMode(STOP_PIN,INPUT_PULLUP);

  digitalWrite(STBY,LOW);
  digitalWrite(IN1,LOW);
  digitalWrite(IN2,LOW);

  if(!ledcAttach(PWM_PIN,20000,8)){
    Serial.println("PWM initialization failed");
    while(true)delay(1000);
  }

  motorOff();

  pinMode(ENC_A,INPUT_PULLUP);
  pinMode(ENC_B,INPUT_PULLUP);

  lastAB=
    (digitalRead(ENC_A)<<1) |
     digitalRead(ENC_B);

  attachInterrupt(
    digitalPinToInterrupt(ENC_A),
    encoderISR,CHANGE
  );

  attachInterrupt(
    digitalPinToInterrupt(ENC_B),
    encoderISR,CHANGE
  );

  Wire.begin(21,22);

  if(!tof.begin()){
    Serial.println("Distance sensor not found");
    while(true)delay(1000);
  }

  WiFi.mode(WIFI_AP);

  WiFi.softAP(
    "ESP32-Tracker",
    "TrackerLab123"
  );

  server.on("/",HTTP_GET,[](){
    server.send_P(
      200,"text/html",PAGE
    );
  });

  server.on("/data",HTTP_GET,handleData);
  server.on("/arm",HTTP_POST,handleArm);
  server.on("/stop",HTTP_POST,handleStop);
  server.on("/mode",HTTP_POST,handleMode);
  server.on("/reset",HTTP_POST,handleReset);

  server.begin();

  xTaskCreatePinnedToCore(
    sensorTask,"Sensor",4096,
    nullptr,1,nullptr,0
  );

  xTaskCreatePinnedToCore(
    motorTask,"Motor",4096,
    nullptr,3,nullptr,1
  );

  Serial.print("Dashboard: http://");
  Serial.println(WiFi.softAPIP());
}

void loop() {
  server.handleClient();
  delay(2);
}

Understanding the firmware

The firmware combines several concepts from the previous articles.

Sensor acquisition

The sensor task acquires distance measurements approximately every 50 milliseconds.

Measurements are rejected when the sensor reports an invalid reading or the target falls outside our selected usable window.

Position filtering

An exponential moving average smooths the distance measurements.

This reduces some of the noise that would otherwise affect the calculated velocity.

Velocity estimation

The program differentiates the filtered position measurements using the actual elapsed time between successive valid readings.

Prediction

The current filtered position is projected 120 milliseconds into the future using the estimated velocity.

Predicted positions are constrained to our configured distance range.

Motion profiling

The desired motor angle passes through a velocity- and acceleration-limited reference generator.

This avoids immediately commanding a large positional jump.

Motor feedback

The rotary encoder provides the shaft's relative angular position.

The controller differentiates this position to estimate angular velocity.

PID control

The motor command combines proportional position correction, optional integral action and derivative damping based on measured velocity.

The initial integral gain is zero. PID gains require hardware-specific tuning.

Safety supervision

The controller starts disabled, checks the stop input, monitors relative travel, rejects stale sensor data and includes basic encoder-progress monitoring.

The firmware is not a safety-rated controller. It cannot guarantee safe operation if a hardware fault, firmware failure or mechanical obstruction occurs.


8. Powering Up the Combined System

Before connecting the motor supply, confirm that the Part 3 motor controller operates correctly by itself.

In particular, verify the direction of the encoder feedback.

An incorrect feedback direction can cause the controller to accelerate away from the target.

For this combined build, keep the motor supply disconnected while initially testing the sensor, dashboard and encoder data.

Upload the firmware through the Arduino IDE.

Open the Serial Monitor at 115200 baud.

The ESP32 should create a Wi-Fi access point.

Connect to:

Network: ESP32-Tracker

Password: TrackerLab123

Open:

http://192.168.4.1

The dashboard should display the sensor measurements.

The motor controller starts disabled.

Initial test sequence

First, position the target approximately 200 mm from the sensor.

The corresponding motor target should be close to zero degrees.

Align the physical pointer with its zero-degree reference before powering the controller.

Check that the displayed motor position agrees with the intended zero reference.

With the motor still isolated from its supply, inspect the sensor measurements and target-angle calculation.

Once those checks pass, connect the current-limited motor supply.

Keep the mechanism unloaded and clear of obstructions.

Enable the controller and move the target only a small distance initially.

Increase the movement range gradually as the controller's behaviour is validated.

If the motor moves unexpectedly, isolate the motor supply immediately.


9. Experiment 1: Tracking Without Prediction

Our first experiment establishes a baseline.

Disable prediction using the dashboard.

Move the target slowly towards and away from the sensor.

The controller will use the filtered measured position directly.

Observe the following:

  • How quickly the motor responds to movement.
  • Whether the pointer lags behind the target.
  • Whether the motor overshoots after the target stops.
  • How smoothly the pointer changes direction.

Record a short dataset and export the measurements.

This gives us a reference against which predictive operation can be compared.

What should we expect?

There will probably be some delay between movement of the target and movement of the pointer.

The delay may come from several sources:

  1. Sensor measurement time.
  2. Filtering.
  3. Sampling intervals.
  4. Motion-profile limitations.
  5. Motor inertia and gearbox behaviour.
  6. PID-controller tuning.

Some of these delays may be reduced through hardware or software improvements.

Others are inherent to the physical system.


10. Experiment 2: Enabling Prediction

Now enable prediction.

The software will estimate where the target may be 120 milliseconds after the current measurement.

Suppose the target is moving away from the sensor.

The predicted distance will be greater than the filtered measured distance.

The motor will therefore receive a target angle slightly ahead of the measured position.

This may improve tracking during approximately constant-speed movement.

Repeat the same experiment as before.

Try to move the target at a similar speed and over the same distance.

Then compare the recordings.

What should improve?

If the prediction horizon compensates for some of the system delay, the actual motor position may follow the real target more closely.

We could observe a reduction in tracking error.

However, the effect will depend on the sensor filtering and motor dynamics.

A poorly chosen prediction horizon may produce overshoot or oscillation.

Prediction is not automatically an improvement.

It is a hypothesis that must be tested.


11. Experiment 3: Testing Different Prediction Horizons

The software uses:

LOOKAHEAD_S = 0.12f

This represents 120 milliseconds.

We can compare several different values.

Prediction horizonBehaviour to investigate
0 msBaseline: no prediction
50 msSmall amount of extrapolation
100 msModerate prediction
120 msInitial reference setting
200 msMore aggressive prediction
300 msGreater risk of prediction error

For each test, record the target movement and motor response.

Ideally, use a repeatable mechanical target-motion profile.

We should avoid relying entirely on subjective observations such as whether the pointer appears smoother.

Instead, we can calculate tracking error.

The instantaneous error is:

Tracking error = Required angle based on actual target position − Measured motor angle

We can then calculate the mean absolute tracking error over an experiment.

A lower mean absolute error indicates better average tracking performance for that particular test.

We should also examine maximum error, overshoot and settling time.

The best prediction horizon may vary with target speed and motion pattern.


12. Experiment 4: What Happens When the Target Changes Direction?

Constant-velocity prediction assumes that an object continues moving at approximately the same speed.

But real movement is rarely that simple.

Suppose the target is moving away from the sensor.

The ESP32 estimates a positive velocity and predicts a future position farther away.

The target then suddenly stops or reverses.

For a short period, the prediction may continue pointing in the original direction.

Consequently, the motor may move towards a position the target never reaches.

This is one of the limitations of simple linear extrapolation.

We can investigate it by moving the target towards the sensor and then reversing direction.

Compare the motor's response with prediction enabled and disabled.

A longer prediction horizon may exaggerate the resulting error.

This experiment demonstrates why more sophisticated prediction systems need to account for uncertainty and changing motion.


13. Experiment 5: Adding Acceleration to the Prediction

Once velocity-only prediction has been evaluated, we can investigate a constant-acceleration model.

Instead of assuming that velocity remains unchanged, we estimate how rapidly velocity is changing.

The prediction equation becomes:

Predicted position = x + vT + ½aT²

For example:

Current position = 0.40 m

Current velocity = 0.20 m/s

Acceleration = 0.50 m/s²

Prediction horizon = 0.20 seconds.

Then:

Predicted position = 0.40 + (0.20 × 0.20) + (0.5 × 0.50 × 0.20²)

Predicted position = 0.45 m

For comparison, the constant-velocity model predicts:

0.40 + (0.20 × 0.20) = 0.44 m.

The acceleration model predicts an additional 10 mm of movement.

Whether that is more accurate depends on the quality of the acceleration estimate.

With noisy sensor readings, acceleration-based prediction can perform worse than the simpler model.

We would therefore need to introduce more sophisticated filtering and test both approaches using the same reference movements.


14. Investigating Prediction Error

One of the most valuable extensions would be to evaluate prediction accuracy directly.

Instead of only measuring motor tracking performance, we can compare predicted target positions with the target's later measured positions.

For example, suppose we make a prediction for 120 milliseconds into the future.

We should compare that prediction against a measurement obtained approximately 120 milliseconds later.

Because our measurements are discrete and not perfectly periodic, we need to use timestamps and interpolate or select an appropriately aligned measurement.

This produces a prediction residual:

Prediction residual = Actual future position − Predicted position

A well-performing predictor should produce relatively small residuals over the types of movement it is designed to handle.

We could calculate:

  • Mean absolute prediction error.
  • Root mean squared prediction error.
  • Maximum prediction error.
  • Error during acceleration.
  • Error during changes of direction.

This would allow us to distinguish two different problems.

One is poor motion prediction.

The other is poor motor tracking.

Both can affect the final system, but they require different solutions.


15. Visualising the Experimental Results

The dashboard displays three useful signals:

  1. The angle corresponding to the currently measured target distance.
  2. The angle requested from the motor controller.
  3. The motor's actual angular position.

When prediction is disabled, the target angle represents the latest filtered measurement.

When prediction is enabled, the target angle is based on the forecast position.

The motion-profile reference can differ from both because it limits how quickly the commanded movement changes.

The browser can export recorded values as a CSV file.

For more detailed analysis, we should use an external program such as Python.

Python example

import pandas as pd
import matplotlib.pyplot as plt

data = pd.read_csv("tracking.csv")

time_s = (
    data["time"] - data["time"].iloc[0]
) / 1000.0

plt.plot(
    time_s,
    data["measuredAngle"],
    label="Measured target position"
)

plt.plot(
    time_s,
    data["target"],
    label="Controller target"
)

plt.plot(
    time_s,
    data["actual"],
    label="Actual motor position"
)

plt.xlabel("Time (seconds)")
plt.ylabel("Angle (degrees)")
plt.title("Predictive Motion Tracking")
plt.legend()
plt.grid(True)
plt.show()

The resulting graph lets us compare the target movement with the motor's response.

For a more rigorous investigation, we should record data directly on the ESP32 with acquisition timestamps rather than rely on the dashboard's browser-side sampling.

The browser records fewer points than the controller processes, so its exported dataset is suitable mainly for introductory visualisation.


16. Safety and Reliability

The combined system introduces additional risks compared with the earlier projects.

The controller now responds automatically to external measurements.

An unexpected sensor reading could produce an unexpected motor command.

For this reason, the design includes several protective behaviours.

Sensor validity checking

The program rejects measurements outside a defined usable range.

It also checks the sensor's reported measurement status.

Stale-data detection

If the controller does not receive a valid sensor measurement within its timeout window, it disables motor output and latches a fault.

Position limits

Motor targets are restricted to 0–180 degrees.

The controller also monitors for excessive measured movement outside the intended range.

These software limits are relative to the initial encoder position. They do not replace mechanical protection.

Encoder monitoring

The program checks whether encoder progress occurs when substantial motor power is requested.

This provides limited protection against a disconnected encoder or stalled motor.

It is not a substitute for current monitoring or physical motor-power isolation.

Manual stop

The project includes a software stop button and a physical motor-supply isolation switch.

The physical switch is essential because software may fail or become unresponsive.

Mechanical considerations

The pointer should be lightweight, securely attached and free to move without encountering a rigid obstruction.

Avoid attaching loads that could cause injury or damage if the controller behaves unexpectedly.

This design is an educational laboratory controller, not a safety-certified autonomous machine.


17. Possible Future Improvements

There are several ways we could develop the system further.

Adaptive prediction

Rather than using a fixed 120 ms prediction horizon, the software could estimate an appropriate horizon based on measured system response.

This could allow the controller to compensate for changing delays.

However, adaptive prediction must be tested carefully because an incorrect estimate could make tracking unstable.

Kalman filtering

A Kalman filter could estimate position and velocity from noisy distance measurements.

This would allow us to combine measurements with a mathematical model of target movement.

A suitable filter might improve velocity estimates, especially when the target moves relatively smoothly.

Model predictive control

Model predictive control, or MPC, is a more advanced technique.

Instead of simply estimating the target's future position, MPC uses a model of the controlled system to evaluate possible future control actions.

It chooses a control action based on an optimisation objective and constraints.

A basic MPC implementation could take account of motor speed, acceleration, position limits and tracking error.

However, it requires a sufficiently accurate model of the motor and careful consideration of computation time.

Our present system is not MPC; it is velocity-based target extrapolation combined with feedback control.

Two-axis tracking

We could replace the single distance sensor with a sensing arrangement capable of detecting target direction.

For example, a camera could provide horizontal and vertical target coordinates.

Two motorised axes could then adjust a pan-and-tilt mechanism.

This would extend our project from one-dimensional motion tracking to two-dimensional visual tracking.

The additional sensing, processing and mechanical complexity would be considerable, but the underlying feedback principles would remain relevant.

Condition monitoring

A further experiment could add motor-current and temperature measurements.

The ESP32 could investigate whether increased current, changes in tracking error or altered response times indicate mechanical resistance or deterioration.

This would introduce a connection to predictive maintenance and fault detection.


18. What Have We Learned Across the Four Projects?

Our series has gradually developed a complete sensing and control system.

PartMain conceptPractical result
Part 1Differentiation and ESP32 fundamentalsUnderstanding the engineering possibilities
Part 2Numerical differentiation and filteringMeasuring position, velocity, acceleration and jerk
Part 3PID feedback and motor controlRegulating angular position using encoder feedback
Part 4Motion prediction and trackingUsing estimated future position to command a controlled motor

The relationship between these stages is important.

Differentiation allows us to estimate how movement changes.

Filtering makes those derivative estimates more useful.

Prediction uses the estimates to calculate possible future movement.

Control theory allows us to command a physical system to respond.

Feedback measures what actually happened and allows the controller to correct its behaviour.

Together, these concepts form the foundation of many more advanced systems.


Conclusion

By combining the ESP32 motion analyser and motor controller, we have developed a system that can measure movement, estimate velocity, predict a short distance into the future and command a motor-driven pointer to respond.

The project introduces an important engineering principle: reacting to the latest measurement is not always the best way to control a moving system.

Where delays exist, information about motion can sometimes help us anticipate future positions and improve tracking.

However, prediction also introduces uncertainty.

A simple constant-velocity model may work well during steady movement but perform poorly when the target suddenly stops or reverses.

That is why experimental validation is essential.

The real value of this project is not simply producing a pointer that follows an object.

It is creating a platform where we can examine the relationship between sensor noise, differentiation, prediction, controller performance and physical movement.

Those same principles are relevant to robotics, automation, motion-control systems and many other areas of engineering.

Our next development could involve replacing the simple velocity predictor with a Kalman-filtered estimator, adding current sensing or implementing a more sophisticated predictive controller.

For now, we have demonstrated how a small ESP32 can combine measurement, mathematics and feedback to create a system that does more than respond to movement.

It begins to anticipate it.


Technical References

Engineering and publication note: The accompanying illustration is conceptual artwork, not a photograph of a completed working prototype. The firmware is a reference implementation and has not been compiled or validated on the assembled hardware as part of this article. Electrical connections, motor polarity, encoder feedback, mechanical travel, operating limits and controller performance must be independently verified before use.

← All articles

Related articles