Part 2 of our ESP32 Calculus and Control Engineering Series
Turn an inexpensive microcontroller and laser distance sensor into a real-time measurement instrument that demonstrates how differentiation works in the physical world.
Introduction
In Part 1 of this series, we explored how differentiation could be combined with an ESP32 microcontroller to create two interesting engineering projects: a real-time motion analyser and an intelligent motor controller.
Now we are going to build the first of those projects.
Our objective is to construct a device that measures the position of an object and continuously calculates its velocity, acceleration and jerk.
Rather than simply displaying the distance to an object, our ESP32 will process successive sensor readings, apply numerical differentiation and display the results through a local OLED screen and a live browser-based dashboard.
We will also investigate one of the most important challenges associated with digital differentiation: measurement noise.
By the end of the project, we will have an instrument capable of demonstrating calculus experimentally, collecting measurements and exporting data for further analysis.
Best of all, it will operate independently, without requiring a computer to perform the calculations.
1. What Are We Going to Build?
The completed system will consist of three main components:
- An ESP32 microcontroller.
- A VL53L0X laser distance sensor.
- An optional SSD1306 OLED display.
The sensor measures the distance between itself and a target object.
The ESP32 records these measurements at regular intervals and calculates the rate at which the distance changes.
From this information, it estimates four quantities:
| Measurement | Description | Units |
|---|---|---|
| Position | Distance between the sensor and object | mm |
| Velocity | Rate of change of position | m/s |
| Acceleration | Rate of change of velocity | m/s² |
| Jerk | Rate of change of acceleration | m/s³ |
We will also create a Wi-Fi network directly from the ESP32.
Connecting a phone, tablet or laptop to this network will allow us to open a dashboard containing four live graphs.
The dashboard will show how the measurements change as we move an object towards or away from the sensor.
It will also provide an option to export the recorded measurements as a CSV file.
How the system works
The measurement process follows this sequence:
Moving Object
|
v
+-----------------+
| VL53L0X Sensor |
+-----------------+
|
I2C Distance
Measurements
|
v
+-----------------+
| ESP32 |
+-----------------+
|
Filter Position
|
v
Calculate Velocity
|
v
Calculate Acceleration
|
v
Calculate Jerk
|
+------+------+
| |
v v
OLED Screen Wi-Fi Dashboard
|
v
CSV Export
The calculation process occurs on the ESP32 itself. The browser is only responsible for displaying the results.
This distinction is important because it means our measurements do not depend on the performance or responsiveness of the connected device.
2. Hardware Requirements
For this project, we will use readily available electronic components.
| Component | Quantity | Purpose |
|---|---|---|
| ESP32 DevKit V1 or compatible original ESP32 development board | 1 | Main processor |
| VL53L0X time-of-flight sensor breakout | 1 | Distance measurement |
| SSD1306 128×64 I²C OLED display | 1 | Local results display |
| Breadboard | 1 | Prototyping |
| Jumper wires | 8–12 | Connections |
| USB cable | 1 | Power and programming |
| Flat, light-coloured target | 1 | Measurement experiments |
The OLED display is optional. The web dashboard will work without it.
Why use the ESP32?
The ESP32 provides several useful features:
- A sufficiently powerful processor for numerical calculations.
- Digital I²C communication for connecting sensors.
- Built-in Wi-Fi networking.
- Adequate memory for storing measurement history.
- Support for the Arduino development environment.
The ESP32 can handle the sensing, calculations, display and network communications in one compact device.
For this build, we will assume a conventional original ESP32 DevKit with GPIO 21 and GPIO 22 available. ESP32-C3, S3 and other variants may require different pin assignments.
Why use the VL53L0X?
The VL53L0X is a time-of-flight distance sensor manufactured by STMicroelectronics.
It uses infrared light to estimate the distance between the sensor and a target.
It communicates digitally using the I²C interface, making it relatively straightforward to connect to an ESP32.
The sensor is specified with a typical ranging timing budget of approximately 33 milliseconds.
For our experiment, we will attempt to collect a measurement every 50 milliseconds, giving a nominal sampling rate of 20 measurements per second.
Our initial operating window will be approximately 40–1,200 mm. This is a deliberately restricted experimental range, not the sensor's absolute specified range.
Actual measurement performance depends on target reflectivity, ambient light and other operating conditions.
We should use a flat, light-coloured target for initial testing.
An important limitation: The VL53L0X is suitable for demonstrating slow movement and numerical differentiation. It is not a high-speed precision motion sensor, and its higher-order derivative estimates should be treated as experimental rather than calibrated measurements.
3. Wiring the Components
We will connect the distance sensor and OLED display to the same I²C bus.
I²C allows multiple compatible devices to communicate through two signal wires, provided they have different device addresses.
VL53L0X connections
| Sensor pin | ESP32 connection |
|---|---|
| VIN | 3.3V |
| GND | GND |
| SDA | GPIO 21 |
| SCL | GPIO 22 |
OLED connections
| OLED pin | ESP32 connection |
|---|---|
| VCC | 3.3V |
| GND | GND |
| SDA | GPIO 21 |
| SCL | GPIO 22 |
The VL53L0X normally uses I²C address 0x29.
Many SSD1306 OLED displays use address 0x3C, although some modules use 0x3D.
Because the devices normally have different addresses, they can share the I²C bus.
Wiring overview
ESP32 DevKit
+----------------+
| |
3.3V --+----------------+----+
| | |
GND --+----------------+--+ |
| | | |
GPIO 21 -+--- SDA | | |
GPIO 22 -+--- SCL | | |
+----------------+ | |
| |
+----------------+ |
| |
+------+-----+ +-----+------+
| VL53L0X | | SSD1306 |
| | | OLED |
| VIN GND | | VCC GND |
| SDA SCL | | SDA SCL |
+------------+ +------------+
Both devices share SDA and SCL.
Both devices share 3.3V and GND.
This diagram is conceptual; follow the pin tables for the actual connections.
Check the voltage requirements of your particular breakout boards before applying power. The ESP32 GPIO pins are not 5V tolerant, and any I²C pull-up resistors must not pull the signals above the permitted GPIO voltage.
The sensor should also be mounted securely. Movement of the sensor itself would affect the distance measurements and could be mistaken for movement of the target.
4. Installing the Software
We will program the ESP32 using the Arduino IDE.
Step 1: Install Arduino IDE
Download the Arduino IDE from:
Install the latest supported version for your computer.
Step 2: Install ESP32 board support
Open Arduino IDE and navigate to:
File → Preferences
Add the Espressif ESP32 Boards Manager URL:
https://espressif.github.io/arduino-esp32/package_esp32_index.json
Next, open:
Tools → Board → Boards Manager
Search for esp32 and install esp32 by Espressif Systems.
Select the correct board under Tools → Board. For a conventional ESP32 DevKit, ESP32 Dev Module is usually an appropriate starting selection.
Step 3: Install the libraries
Open:
Sketch → Include Library → Manage Libraries
Install:
- Adafruit VL53L0X
- Adafruit SSD1306
- Adafruit GFX Library
Install any dependencies requested by the Arduino Library Manager.
The ESP32 board package already provides the Wi-Fi and basic web-server libraries used in this project.
Step 4: Test the sensor
Before introducing our mathematical calculations, verify that the sensor is operating correctly.
Open the example:
File → Examples → Adafruit VL53L0X → vl53l0x
Upload it to the ESP32 and open the Serial Monitor.
The program should display distance measurements as you move an object in front of the sensor.
If the measurements are missing or unreasonable, check the wiring and power connections before proceeding.
There is little value in debugging differentiation calculations until the underlying sensor measurements are reliable.
5. Understanding the Calculations
Our program will receive a succession of distance measurements.
Suppose these are the readings from a moving target:
| Time | Position |
|---|---|
| 0.00 s | 600 mm |
| 0.05 s | 590 mm |
| 0.10 s | 575 mm |
| 0.15 s | 555 mm |
| 0.20 s | 530 mm |
The object is moving towards the sensor.
Notice that its position is changing more rapidly with each successive measurement.
This suggests that the object is accelerating.
Calculating velocity
Velocity is the first derivative of position:
v = dx/dt
With discrete measurements, we estimate velocity using:
v ≈ (x₂ − x₁) / (t₂ − t₁)
Between 0.00 and 0.05 seconds:
v = (590 − 600) / 0.05
v = −200 mm/s
Between 0.05 and 0.10 seconds:
v = (575 − 590) / 0.05
v = −300 mm/s
The magnitude of the velocity is increasing.
The negative sign indicates movement towards the sensor.
Calculating acceleration
Acceleration is the derivative of velocity:
a = dv/dt
We can approximate it using:
a ≈ (v₂ − v₁) / (t₂ − t₁)
Using the two velocity estimates:
a = (−300 − (−200)) / 0.05
a = −2,000 mm/s²
Therefore:
a = −2.0 m/s²
The object is accelerating towards the sensor.
Calculating jerk
Jerk is the derivative of acceleration:
j = da/dt
Jerk describes how quickly acceleration changes.
It is particularly relevant in applications involving smooth mechanical movement, including robotics, motion-control systems and passenger transport.
A rapidly changing acceleration can produce abrupt movement, even when the overall speed remains relatively low.
Our program will estimate jerk from successive acceleration values.
There is a complication, however.
Numerical differentiation makes measurement noise increasingly significant as we calculate higher-order derivatives.
That is the next problem we need to address.
6. Why We Need to Filter the Measurements
Imagine holding a flat object perfectly still, 500 mm from the sensor.
Ideally, every measurement would read exactly 500 mm.
In practice, we might obtain:
Measurement 1: 500 mm
Measurement 2: 502 mm
Measurement 3: 499 mm
Measurement 4: 501 mm
Measurement 5: 500 mm
The object has not moved, but the sensor measurements have fluctuated.
Consider just the first two readings.
The apparent displacement is 2 mm.
With a measurement interval of 50 milliseconds:
Velocity = 0.002 / 0.05
Apparent velocity = 0.04 m/s
Our calculations would incorrectly suggest that the object was moving.
Differentiating this noise again can produce even larger apparent acceleration and jerk values.
This is not a fault in calculus.
It is a consequence of applying numerical differentiation to imperfect measurements.
Introducing an exponential moving average
One relatively simple filtering method is the exponential moving average, or EMA.
It combines the latest sensor reading with the previous filtered value.
The equation is:
Filtered value = α × new reading + (1 − α) × previous filtered value
The parameter α controls the amount of smoothing.
A value approaching 1 responds quickly to new measurements but provides relatively little filtering.
A smaller value produces smoother results at the expense of additional delay.
For our initial project, we will use:
Position filter α = 0.25
We will also apply additional smoothing to the calculated velocity, acceleration and jerk.
This approach is easy to implement, although it is not necessarily the most accurate derivative estimator.
Later, we can compare it against more sophisticated techniques such as polynomial fitting and Savitzky–Golay differentiation.
7. Writing the ESP32 Program
We are now ready to implement the complete system.
Our program must perform several tasks:
- Read the VL53L0X sensor.
- Validate each measurement.
- Apply position filtering.
- Calculate velocity, acceleration and jerk.
- Update the OLED screen.
- Create a Wi-Fi network.
- Host a dashboard.
- Store a rolling history of measurements.
- Allow that history to be exported as CSV data.
For simplicity, we will use one Arduino sketch.
The browser dashboard will be embedded directly into the firmware, so no separate web-hosting service or internet connection is necessary.
Complete Arduino sketch
Create a new sketch called ESP32_Motion_Analyser and replace its contents with the following code.
#include <Arduino.h>
#include <Wire.h>
#include <WiFi.h>
#include <WebServer.h>
#include <Adafruit_VL53L0X.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
// Hardware
Adafruit_VL53L0X tof;
Adafruit_SSD1306 oled(128, 64, &Wire, -1);
WebServer server(80);
// Standalone Wi-Fi access point
const char* AP_NAME = "ESP32-Motion";
const char* AP_PASS = "MotionLab123";
// Sampling and filtering
const uint32_t SAMPLE_MS = 50;
const float POSITION_ALPHA = 0.25f;
const float DERIV_ALPHA = 0.20f;
// Valid experimental distance window
const uint16_t MIN_MM = 40;
const uint16_t MAX_MM = 1200;
// Rolling log: approximately 30 seconds
const int LOG_SIZE = 600;
struct Sample {
uint32_t t_ms;
float raw_mm;
float filtered_mm;
float v;
float a;
float j;
};
Sample logData[LOG_SIZE];
int logNext = 0;
int logCount = 0;
// Measurement state
bool valid = false;
bool havePrevious = false;
bool oledPresent = false;
float rawMM = 0;
float positionM = 0;
float velocity = 0;
float acceleration = 0;
float jerk = 0;
uint32_t previousUs = 0;
uint32_t lastSampleMs = 0;
uint32_t lastOledMs = 0;
// Embedded web page
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 Motion Analyser</title>
<style>
body {
margin: 0;
font-family: Arial, sans-serif;
background: #f3f5f8;
color: #202938;
}
main {
max-width: 950px;
margin: auto;
padding: 20px;
}
h1 { margin-bottom: 5px; }
.cards {
display: grid;
grid-template-columns:
repeat(auto-fit, minmax(150px, 1fr));
gap: 12px;
}
.card, .graph {
background: white;
padding: 17px;
border-radius: 12px;
margin-bottom: 14px;
box-shadow: 0 1px 5px #0001;
}
.card strong {
display: block;
font-size: 25px;
margin: 10px 0;
}
small { color: #657085; }
canvas {
width: 100%;
height: 160px;
display: block;
}
a {
display: inline-block;
padding: 12px 18px;
color: white;
background: #245bc4;
text-decoration: none;
border-radius: 8px;
}
</style>
</head>
<body>
<main>
<h1>ESP32 Motion Analyser</h1>
<p id="status">Connecting...</p>
<div class="cards">
<div class="card">
Position
<strong id="p">--</strong>
<small>mm</small>
</div>
<div class="card">
Velocity
<strong id="v">--</strong>
<small>m/s</small>
</div>
<div class="card">
Acceleration
<strong id="a">--</strong>
<small>m/s²</small>
</div>
<div class="card">
Jerk
<strong id="j">--</strong>
<small>m/s³</small>
</div>
</div>
<div class="graph">
<h3>Position (mm)</h3>
<small>Blue = raw, orange = filtered</small>
<canvas id="position"></canvas>
</div>
<div class="graph">
<h3>Velocity (m/s)</h3>
<canvas id="velocity"></canvas>
</div>
<div class="graph">
<h3>Acceleration (m/s²)</h3>
<canvas id="acceleration"></canvas>
</div>
<div class="graph">
<h3>Jerk (m/s³)</h3>
<canvas id="jerk"></canvas>
</div>
<a href="/csv">Download CSV measurements</a>
<p><small>
Positive velocity means moving away from the sensor.
</small></p>
</main>
<script>
const history = [];
const MAX_POINTS = 120;
const configurations = [
["position", ["raw", "filtered"]],
["velocity", ["v"]],
["acceleration", ["a"]],
["jerk", ["j"]]
];
function drawGraph(id, keys) {
const canvas = document.getElementById(id);
const w = Math.max(200, canvas.clientWidth);
const h = 160;
const ratio = window.devicePixelRatio || 1;
canvas.width = Math.floor(w * ratio);
canvas.height = Math.floor(h * ratio);
const ctx = canvas.getContext("2d");
ctx.scale(ratio, ratio);
ctx.clearRect(0, 0, w, h);
const values = history.flatMap(
point => keys.map(key => point[key])
).filter(Number.isFinite);
if (values.length < 2) return;
let minimum = Math.min(...values);
let maximum = Math.max(...values);
let padding = (maximum - minimum) * 0.15 || 1;
minimum -= padding;
maximum += padding;
const left = 50;
const top = 12;
const plotW = w - 60;
const plotH = h - 32;
ctx.strokeStyle = "#e1e5eb";
ctx.lineWidth = 1;
for (let i = 0; i <= 4; i++) {
const y = top + plotH * i / 4;
ctx.beginPath();
ctx.moveTo(left, y);
ctx.lineTo(w - 10, y);
ctx.stroke();
}
ctx.fillStyle = "#555";
ctx.font = "10px Arial";
ctx.fillText(maximum.toFixed(2), 2, 14);
ctx.fillText(minimum.toFixed(2), 2, h - 18);
const colours = ["#2463eb", "#ee8a22"];
keys.forEach((key, seriesIndex) => {
ctx.beginPath();
ctx.strokeStyle = colours[seriesIndex] ||
"#2463eb";
ctx.lineWidth = 2;
history.forEach((point, index) => {
const x = left +
index * plotW /
Math.max(1, history.length - 1);
const y = top + plotH -
(point[key] - minimum) /
(maximum - minimum) * plotH;
if (index === 0) ctx.moveTo(x, y);
else ctx.lineTo(x, y);
});
ctx.stroke();
});
}
async function update() {
try {
const response = await fetch(
"/data", { cache: "no-store" }
);
if (!response.ok) throw new Error("HTTP error");
const d = await response.json();
if (!d.valid) {
document.getElementById("status").textContent =
"No valid target measurement";
for (const id of ["p", "v", "a", "j"]) {
document.getElementById(id).textContent = "--";
}
return;
}
document.getElementById("status").textContent =
"Sensor connected - live measurements";
document.getElementById("p").textContent =
d.filtered.toFixed(1);
document.getElementById("v").textContent =
d.v.toFixed(3);
document.getElementById("a").textContent =
d.a.toFixed(3);
document.getElementById("j").textContent =
d.j.toFixed(3);
history.push(d);
if (history.length > MAX_POINTS) {
history.shift();
}
configurations.forEach(
item => drawGraph(item[0], item[1])
);
} catch (error) {
document.getElementById("status").textContent =
"Connection lost";
}
}
setInterval(update, 150);
update();
</script>
</body>
</html>
)HTML";
// Store one successful measurement
void storeSample() {
Sample &s = logData[logNext];
s.t_ms = millis();
s.raw_mm = rawMM;
s.filtered_mm = positionM * 1000.0f;
s.v = velocity;
s.a = acceleration;
s.j = jerk;
logNext = (logNext + 1) % LOG_SIZE;
if (logCount < LOG_SIZE) {
logCount++;
}
}
// Read sensor and calculate derivatives
void takeMeasurement() {
VL53L0X_RangingMeasurementData_t m;
VL53L0X_Error result =
tof.rangingTest(&m, false);
uint32_t nowUs = micros();
if (result != VL53L0X_ERROR_NONE ||
m.RangeStatus != 0 ||
m.RangeMilliMeter < MIN_MM ||
m.RangeMilliMeter > MAX_MM) {
valid = false;
havePrevious = false;
return;
}
valid = true;
rawMM = float(m.RangeMilliMeter);
float rawM = rawMM / 1000.0f;
if (!havePrevious) {
positionM = rawM;
velocity = 0;
acceleration = 0;
jerk = 0;
havePrevious = true;
} else {
float dt =
float(uint32_t(nowUs - previousUs))
/ 1000000.0f;
if (dt <= 0 || dt > 0.25f) {
positionM = rawM;
velocity = 0;
acceleration = 0;
jerk = 0;
} else {
float oldPosition = positionM;
float oldVelocity = velocity;
float oldAcceleration = acceleration;
// Low-pass filter the position
positionM =
POSITION_ALPHA * rawM +
(1.0f - POSITION_ALPHA) * positionM;
// First derivative: velocity
float rawVelocity =
(positionM - oldPosition) / dt;
velocity =
DERIV_ALPHA * rawVelocity +
(1.0f - DERIV_ALPHA) * velocity;
// Second derivative: acceleration
float rawAcceleration =
(velocity - oldVelocity) / dt;
acceleration =
DERIV_ALPHA * rawAcceleration +
(1.0f - DERIV_ALPHA) * acceleration;
// Third derivative: jerk
float rawJerk =
(acceleration - oldAcceleration) / dt;
jerk =
DERIV_ALPHA * rawJerk +
(1.0f - DERIV_ALPHA) * jerk;
}
}
previousUs = nowUs;
storeSample();
Serial.printf(
"x=%.1f mm v=%.3f a=%.3f j=%.3f\n",
positionM * 1000.0f,
velocity,
acceleration,
jerk
);
}
// Update optional OLED display
void updateOLED() {
if (!oledPresent) return;
oled.clearDisplay();
oled.setTextColor(SSD1306_WHITE);
oled.setTextSize(1);
oled.setCursor(0, 0);
oled.println("ESP32 Motion Analyser");
if (!valid) {
oled.setCursor(0, 24);
oled.println("No valid target");
} else {
oled.setCursor(0, 15);
oled.print("X: ");
oled.print(positionM * 1000.0f, 1);
oled.println(" mm");
oled.print("V: ");
oled.print(velocity, 3);
oled.println(" m/s");
oled.print("A: ");
oled.print(acceleration, 3);
oled.println(" m/s2");
oled.print("J: ");
oled.print(jerk, 3);
oled.println(" m/s3");
}
oled.display();
}
// Latest measurement endpoint
void handleData() {
String result = "{\"valid\":";
result += valid ? "true" : "false";
result += ",\"raw\":";
result += String(rawMM, 2);
result += ",\"filtered\":";
result += String(positionM * 1000.0f, 2);
result += ",\"v\":";
result += String(velocity, 5);
result += ",\"a\":";
result += String(acceleration, 5);
result += ",\"j\":";
result += String(jerk, 5);
result += "}";
server.send(200, "application/json", result);
}
// Export rolling measurement history
void handleCSV() {
server.sendHeader(
"Content-Disposition",
"attachment; filename=motion.csv"
);
server.setContentLength(CONTENT_LENGTH_UNKNOWN);
server.send(
200,
"text/csv",
"time_ms,raw_mm,filtered_mm,"
"velocity_mps,acceleration_mps2,"
"jerk_mps3\n"
);
int oldest =
(logNext - logCount + LOG_SIZE) % LOG_SIZE;
for (int i = 0; i < logCount; i++) {
int index = (oldest + i) % LOG_SIZE;
Sample &s = logData[index];
String line = String(s.t_ms);
line += "," + String(s.raw_mm, 2);
line += "," + String(s.filtered_mm, 2);
line += "," + String(s.v, 5);
line += "," + String(s.a, 5);
line += "," + String(s.j, 5);
line += "\n";
server.sendContent(line);
}
server.sendContent("");
}
void setup() {
Serial.begin(115200);
Wire.begin(21, 22);
if (!tof.begin()) {
Serial.println("VL53L0X not detected");
while (true) delay(1000);
}
oledPresent =
oled.begin(SSD1306_SWITCHCAPVCC, 0x3C);
WiFi.mode(WIFI_AP);
if (!WiFi.softAP(AP_NAME, AP_PASS)) {
Serial.println("Wi-Fi AP failed");
}
Serial.print("Dashboard: http://");
Serial.println(WiFi.softAPIP());
server.on("/", HTTP_GET, []() {
server.send_P(200, "text/html", PAGE);
});
server.on("/data", HTTP_GET, handleData);
server.on("/csv", HTTP_GET, handleCSV);
server.begin();
Serial.println("Motion analyser ready");
}
void loop() {
server.handleClient();
uint32_t nowMs = millis();
if (nowMs - lastSampleMs >= SAMPLE_MS) {
lastSampleMs = nowMs;
takeMeasurement();
}
if (nowMs - lastOledMs >= 250) {
lastOledMs = nowMs;
updateOLED();
}
}
Understanding the sketch
Although the program is relatively long, it contains only a few important functional sections.
Sensor acquisition
The takeMeasurement() function reads the distance sensor and checks whether the returned measurement is valid.
Measurements outside our chosen operating window are rejected.
The program also resets its differentiation state after an invalid measurement, preventing a long interruption from being interpreted as an instantaneous movement.
Time measurement
The program uses micros() to calculate elapsed time between successful readings.
This is more accurate than assuming the sampling interval is always exactly 50 milliseconds.
Filtering
The position measurement is filtered before differentiation.
The calculated velocity, acceleration and jerk are also smoothed.
These additional filters make the displayed signals easier to interpret, although they introduce delay and can attenuate genuine rapid motion.
Measurement logging
The program maintains a circular buffer containing the most recent 600 successful measurements.
At the nominal 20 Hz sampling rate, this corresponds to approximately 30 seconds of data.
Invalid measurements are omitted, so the actual recorded period may be longer.
Web dashboard
The embedded webpage retrieves measurement data from the ESP32 every 150 milliseconds.
It then updates the numerical values and draws the graphs using the browser's built-in Canvas API.
Because the webpage does not depend on an external JavaScript library, the dashboard works without an internet connection.
The browser samples the latest calculated values for display, so its history is not necessarily identical to the complete sensor log.
8. Uploading and Running the Program
Connect the ESP32 to your computer using its USB cable.
In Arduino IDE, select the correct board and serial port.
Compile the program and upload it.
After the upload completes, open the Serial Monitor at 115200 baud.
You should see startup information similar to:
Dashboard: http://192.168.4.1
Motion analyser ready
x=501.2 mm v=0.002 a=-0.014 j=0.087
x=500.9 mm v=0.001 a=-0.019 j=0.054
The numerical readings above are illustrative.
Connecting to the dashboard
On a phone, tablet or laptop:
- Open the Wi-Fi settings.
- Find the network called
ESP32-Motion. - Connect using the password
MotionLab123. - Open a web browser.
- Navigate to
http://192.168.4.1.
The dashboard should appear.
You may receive a warning that the network has no internet connection. This is expected because the ESP32 is providing its own local network.
Choose to remain connected.
Security: This demonstration uses a published example password. Change it before using the device in an environment where other people might be within Wi-Fi range. The dashboard uses local HTTP and has no authentication beyond access to the Wi-Fi network.
What should happen?
Hold a flat object approximately 500 mm from the sensor.
The position reading should settle near that value.
Move the object slowly towards the sensor.
The position should decrease, and the calculated velocity should become negative.
Move it away.
The velocity should become positive.
Speed up and slow down, and the acceleration graph should respond accordingly.
The jerk graph may be substantially noisier than the others. We will investigate that behaviour in the next section.
9. Experiment 1: Measuring a Stationary Object
Our first experiment is designed to establish the noise level of the measurement system.
Place the sensor on a stable surface.
Position a flat, light-coloured object approximately 500 mm in front of it.
Keep the object stationary.
Record approximately 30 seconds of data and download the CSV file.
What should we expect?
Ideally:
- Position remains constant.
- Velocity is zero.
- Acceleration is zero.
- Jerk is zero.
In reality, all four signals will fluctuate.
Position may remain relatively stable, while acceleration and jerk show much greater numerical variation.
This demonstrates how differentiation responds to small changes in input measurements.
Analysing the results
Import the CSV file into Excel or Python.
Calculate the mean and standard deviation of the position measurements.
Then repeat the calculations for velocity, acceleration and jerk.
The standard deviation gives us a useful indication of the noise associated with each estimate.
| Quantity | What we are investigating |
|---|---|
| Raw position | Original sensor variation |
| Filtered position | Effectiveness of smoothing |
| Velocity | Noise after first differentiation |
| Acceleration | Noise after second differentiation |
| Jerk | Noise after third differentiation |
The experiment highlights an important engineering principle:
A calculated result can be mathematically correct while being physically misleading if its input measurements contain significant noise.
10. Experiment 2: Measuring Approximately Constant Velocity
For our second experiment, we will move an object steadily towards the sensor.
Ideally, the distance should decrease at a constant rate.
For example, moving 200 mm over two seconds gives an average velocity of:
200 / 2 = 100 mm/s
Therefore:
Velocity = −0.1 m/s
The negative sign indicates movement towards the sensor.
If the movement is sufficiently steady, the recorded position should decrease approximately linearly.
The velocity should remain close to −0.1 m/s.
Acceleration should remain close to zero during the constant-speed portion of the movement.
In practice, moving an object by hand at a perfectly constant speed is difficult.
For better repeatability, we could construct a small linear rail with a moving carriage.
Alternatively, we could use a motor-driven mechanism to move the object at a controlled speed.
That would also provide a useful link to the motor-controller project discussed in Part 1.
11. Experiment 3: Measuring Acceleration
Our third experiment involves deliberately changing the speed of the object.
Start with the target approximately 800 mm from the sensor.
Begin moving it slowly towards the sensor.
Gradually increase its speed, then slow it down before reaching the minimum measurement distance.
Observe how the acceleration graph responds.
During the initial speed increase, the velocity becomes increasingly negative.
The calculated acceleration should also become negative.
During deceleration, the velocity becomes less negative, and acceleration should become positive.
This demonstrates why velocity and acceleration are different physical quantities.
An object can be moving towards the sensor while its acceleration points in the opposite direction.
This happens whenever the object is slowing down.
What about jerk?
Jerk becomes noticeable when the acceleration changes rapidly.
If we move the object smoothly, acceleration should change relatively gradually.
If we abruptly alter the motion, the jerk estimate may exhibit a larger peak.
However, genuine changes in acceleration must be distinguished from noise and filtering effects.
We should therefore avoid interpreting every jerk spike as real physical movement.
12. Experiment 4: Investigating Different Filters
One of the most interesting parts of this project is the opportunity to compare signal-processing techniques.
Our initial program uses:
const float POSITION_ALPHA = 0.25f;
const float DERIV_ALPHA = 0.20f;
These values control the amount of smoothing.
We can experiment with different settings.
| Filter configuration | Expected behaviour |
|---|---|
| α = 1.0 | Minimal smoothing, noisy derivatives |
| α = 0.5 | Faster response, moderate smoothing |
| α = 0.25 | More smoothing and noticeable delay |
| α = 0.1 | Strong smoothing, slower response |
For a controlled experiment, we should change one filter parameter at a time.
For example, set POSITION_ALPHA to 1.0 and leave the derivative filter unchanged.
Collect a stationary-target dataset.
Then repeat with POSITION_ALPHA set to 0.5, 0.25 and 0.1.
We can compare the standard deviation of the velocity, acceleration and jerk estimates.
Next, repeat the experiment using a moving object to investigate how the filters affect responsiveness.
This comparison should reveal a fundamental trade-off.
Strong filtering suppresses noise but can also hide or delay genuine movement.
Weak filtering responds more quickly but produces noisier derivative estimates.
Neither approach is universally correct.
The best solution depends on the intended application.
Going beyond the exponential moving average
For further development, we could implement:
Moving-average filtering
Calculate the average of a fixed number of recent measurements.
Central-difference differentiation
Use measurements before and after a particular point to estimate the derivative at that point.
This is useful for processing recorded data, although obtaining the future measurement introduces latency in real-time applications.
Savitzky–Golay filtering
Fit a polynomial to a group of measurements and use that polynomial to estimate the derivatives.
This approach can be effective when we want to preserve the shape of a changing signal.
Kalman filtering
Use a mathematical model of the system to estimate position and velocity from noisy measurements.
For a more advanced project, we could compare these methods using identical recorded datasets and evaluate their accuracy.
13. Exporting the Measurements to Excel
The dashboard contains a button labelled Download CSV measurements.
Clicking this button downloads the ESP32's rolling measurement history.
The exported file contains the following columns:
time_ms
raw_mm
filtered_mm
velocity_mps
acceleration_mps2
jerk_mps3
Each row represents one successful measurement.
The time column uses milliseconds since the ESP32 started running.
For data analysis, it is generally useful to subtract the first timestamp so that the recording begins at zero seconds.
Creating graphs in Excel
Open the CSV file and create a scatter chart.
Use the timestamp column for the horizontal axis.
Start by plotting raw and filtered position against time.
This allows us to see how filtering affects the original measurements.
Next, plot velocity, acceleration and jerk separately.
We can examine how the signals change during each movement experiment.
It may also be useful to calculate the minimum, maximum, mean and standard deviation of each measurement.
Additional Python analysis
Python offers more flexibility for numerical analysis.
For example:
import pandas as pd
import matplotlib.pyplot as plt
data = pd.read_csv("motion.csv")
time_s = (
data["time_ms"] - data["time_ms"].iloc[0]
) / 1000.0
plt.plot(
time_s,
data["raw_mm"],
label="Raw position"
)
plt.plot(
time_s,
data["filtered_mm"],
label="Filtered position"
)
plt.xlabel("Time (seconds)")
plt.ylabel("Position (mm)")
plt.legend()
plt.grid(True)
plt.show()
This produces a comparison between the original distance measurements and the filtered position estimates.
The analysis could be extended to calculate numerical derivatives independently in Python and compare them with those produced by the ESP32.
For a meaningful comparison, use the actual timestamps rather than assuming that every sample interval is identical.
14. Troubleshooting
Several problems may occur during development.
| Problem | Likely cause and action |
|---|---|
| Sensor not detected | Check power, wiring and I²C connections |
| OLED remains blank | Check its I²C address, voltage and wiring |
| Distance readings fluctuate | Improve target reflectivity and sensor mounting |
| Constant invalid measurements | Move the target into the chosen 40–1,200 mm window |
| Very noisy acceleration | Investigate sensor noise and filtering |
| Large jerk spikes | Check invalid readings, movement discontinuities and derivative noise |
| Dashboard does not open | Confirm Wi-Fi connection and use http://192.168.4.1 |
| Unexpected graph behaviour | Check sampling intervals and filtering parameters |
| Missing CSV samples | Invalid measurements are deliberately omitted |
| Slow dashboard updates | Check Wi-Fi reception, browser performance and measurement timing |
One detail worth investigating is the interaction between sensor sampling and web communication.
Our example uses a straightforward sequential program.
Sensor measurements can block execution temporarily, and serving CSV data also consumes processing time.
For educational use, this is an acceptable starting point.
For more demanding measurement applications, we would benefit from separate acquisition and network tasks, buffered data transfer and a more carefully controlled sampling schedule.
We could also use continuous-ranging mode where supported and appropriate.
15. Improving Measurement Accuracy
There are several ways to improve our experimental system.
Stabilise the sensor
Mount the sensor securely on a rigid support.
Any unintended sensor movement changes the measured distance.
Use a consistent target
A flat, light-coloured target generally provides a more suitable starting point than a dark, angled or highly reflective object.
Reduce environmental interference
Strong ambient light and changing target reflectivity can influence optical ranging performance.
Repeat experiments under consistent conditions.
Measure the real sampling intervals
Although our program attempts to acquire a measurement every 50 milliseconds, actual timing can vary.
The sensor's ranging duration, display updates and web-server activity can all affect timing.
We use micros() to account for the actual elapsed time in the derivative calculations.
For further investigation, we could export the time difference between successive valid samples as an additional CSV column.
Validate against known motion
The most important improvement is to compare the sensor measurements against a known physical reference.
For example, a motor-driven linear carriage with a calibrated movement profile could provide a more consistent test than moving an object by hand.
This would allow us to quantify measurement error rather than judging the graphs purely by appearance.
16. Possible Future Improvements
Once the basic motion analyser is operating, there are several extensions worth investigating.
Upgrade the sensor
We could experiment with a different time-of-flight sensor offering improved ranging performance or measurement frequency.
This could make the system more suitable for observing faster movement.
Add an SD card
Instead of maintaining a limited rolling log in memory, we could write timestamped measurements to an SD card.
This would enable much longer experiments.
Add adjustable filter settings
The web dashboard could allow us to change the filtering coefficients without recompiling the firmware.
This would make comparisons considerably easier.
Implement polynomial differentiation
A particularly useful improvement would be to compare our existing derivative calculations against a Savitzky–Golay implementation.
We could measure the differences in noise, delay and response to known movements.
Develop a physical test rig
A small motorised linear slide could provide repeatable movement at controlled velocities and accelerations.
This would allow much more rigorous experiments.
It would also create a natural connection to our next project.
17. Connecting the Motion Analyser to Our Next Project
In Part 3, we will construct an intelligent motor controller.
Instead of measuring the movement of an external object using a distance sensor, we will measure the movement of a motor shaft using a rotary encoder.
The encoder will provide angular position.
Differentiation will allow us to estimate angular velocity and acceleration.
We will then use that information in a feedback-control system.
The ESP32 will continuously compare the desired motor position with the actual position and adjust the motor's power accordingly.
This introduces PID control, which combines proportional, integral and derivative actions to regulate a system.
Eventually, we could combine the two projects.
The distance sensor could detect the movement of an object.
The motor controller could then adjust a mechanism to follow it.
More advanced software could use the measured velocity to predict where the object is likely to move next.
The result would be a system that does more than react to current measurements.
It could begin anticipating movement.
Conclusion
Our ESP32 motion analyser demonstrates how differential calculus can be applied to real-world measurements.
By connecting a time-of-flight distance sensor to a microcontroller, we can calculate velocity, acceleration and jerk from a stream of positional measurements.
More importantly, the project reveals some of the practical limitations of numerical differentiation.
Real sensors produce noise.
Measurements are taken at discrete intervals.
Filtering introduces delays.
Higher-order derivatives can become increasingly sensitive to small errors.
These are not merely theoretical concerns. They are important considerations in practical measurement and control systems.
The project also provides a foundation for investigating more sophisticated signal-processing techniques, including polynomial differentiation, Kalman filtering and system identification.
In Part 3, we will take the next step and use differentiation to control a physical system rather than simply observe it.
Next: Part 3 — Building an Intelligent ESP32 Motor Controller Using Encoders, Differentiation and PID Feedback.
Technical References
- STMicroelectronics — VL53L0X time-of-flight sensor: https://www.st.com/en/imaging-and-photonics-solutions/vl53l0x.html
- Adafruit — VL53L0X Arduino tutorial: https://learn.adafruit.com/adafruit-vl53l0x-micro-lidar-distance-sensor-breakout
- Espressif — Arduino ESP32 documentation: https://docs.espressif.com/projects/arduino-esp32/en/latest/
- Adafruit — SSD1306 display library: https://github.com/adafruit/Adafruit_SSD1306
- Arduino — Development environment: https://www.arduino.cc/en/software
Engineering note: The firmware is supplied as a reference implementation. Its library interfaces and hardware assumptions have been checked against published documentation, but the complete sketch has not been compiled on a physical ESP32 or validated through hardware testing. Actual results will vary with the components, operating conditions and selected filter parameters. The calculated acceleration and jerk are filtered estimates, not precision-calibrated measurements.