Reading Time: 13 minutes

How to use differentiation, real-time sensors and an ESP32 microcontroller to turn mathematical equations into working electronic systems.

Differentiation is one of the most important concepts in mathematics, but it becomes considerably more interesting when we can observe its effects in the physical world.

We normally encounter differentiation through equations describing how quantities change. Velocity is the rate of change of position. Acceleration is the rate of change of velocity. Even acceleration itself can change, producing a quantity known as jerk.

But what if we could build an electronic system that calculated these quantities continuously?

Better still, what if the system could use those calculations to control a motor, adjust its movements and respond to disturbances?

Using an inexpensive ESP32 microcontroller, sensors and some straightforward programming, we can develop two complementary projects:

  1. A real-time motion analyser that measures distance and calculates velocity, acceleration and jerk.
  2. An intelligent motor controller that uses differentiation and feedback control to regulate physical movement.

The first project helps us understand the mathematics. The second demonstrates how that mathematics becomes useful in robotics, automation and engineering.

Both projects can be constructed independently and eventually combined into a more advanced experimental platform.


Understanding the Mathematics

Before building anything, we need to understand what the ESP32 will calculate.

Consider an object moving along a straight line. Its position changes over time.

We describe its position as x(t), where x is the position and t represents time.

The first derivative of position gives velocity:

Velocity = dx/dt

The second derivative gives acceleration:

Acceleration = d²x/dt²

The third derivative gives jerk:

Jerk = d³x/dt³

In a perfect mathematical model, these quantities can be calculated analytically. However, a microcontroller receives individual measurements rather than a continuous mathematical function.

We therefore use numerical differentiation.

For example, suppose a sensor measures an object at 500 mm and, 100 milliseconds later, measures it at 450 mm.

The change in position is:

450 − 500 = −50 mm

The elapsed time is 0.1 seconds.

Therefore:

Velocity = −50 / 0.1 = −500 mm/s

The negative value indicates movement towards the sensor.

By continuing to record measurements, we can calculate how velocity changes and derive acceleration.

This is the fundamental principle behind our projects.


Project 1: Building a Real-Time Motion Analyser

What are we building?

Our first system will use a laser distance sensor connected to an ESP32.

The sensor repeatedly measures the distance to an object. The ESP32 processes the measurements, calculates their derivatives and makes the results available through a display or web interface.

For example, when moving a hand backwards and forwards in front of the sensor, the system will show how its position, velocity and acceleration change.

The objective is to create a working demonstration of differential calculus using real measurements.

Hardware requirements

ComponentPurpose
ESP32 DevKit development boardMain microcontroller
VL53L0X time-of-flight distance sensor breakoutMeasures distance
SSD1306 128×64 OLED displayDisplays results locally
BreadboardPrototyping
Jumper wiresElectrical connections
USB cable and power supplyPowers the ESP32
Computer with Arduino IDEProgramming and testing

The VL53L0X is an optical time-of-flight sensor manufactured by STMicroelectronics. It measures distance using reflected infrared light.

Unlike a basic ultrasonic sensor, it uses a compact optical ranging system and communicates digitally through I²C.

The sensor typically uses a 33 ms measurement timing budget, making a sampling interval around 50 ms a sensible starting point for this project.

The sensor is suitable for observing relatively slow movements, although it is not a precision motion-capture instrument.

Step 1: Connecting the hardware

For this demonstration, we will use a conventional ESP32 DevKit based on the original ESP32.

The VL53L0X breakout connects as follows:

VL53L0XESP32
VIN3.3V
GNDGND
SDAGPIO 21
SCLGPIO 22

The OLED display can share the same I²C communication lines:

OLED displayESP32
VCC3.3V
GNDGND
SDAGPIO 21
SCLGPIO 22

Use breakout boards confirmed to support 3.3V operation. The VL53L0X typically uses I²C address 0x29, while many SSD1306 modules use 0x3C.

Because the devices have different addresses, the ESP32 can communicate with both over the same wires.

Once connected, we can test the distance sensor before attempting any mathematical calculations.

Step 2: Preparing the programming environment

Install the Arduino IDE and add Espressif's ESP32 board package through the Boards Manager.

Next, install the following libraries through the Library Manager:

  • Adafruit VL53L0X
  • Adafruit GFX Library
  • Adafruit SSD1306

The last two are only required when using the optional OLED display.

We should begin with the example program included in the Adafruit VL53L0X library.

This verifies that the sensor communicates with the microcontroller and produces sensible distance measurements.

At this stage, a stationary object should generate relatively consistent readings in millimetres.

Step 3: Calculating velocity

Once the distance sensor works, we can start differentiating its measurements.

The basic algorithm is straightforward:

  1. Read the current distance.
  2. Record the measurement time.
  3. Subtract the previous distance from the current distance.
  4. Divide the difference by the elapsed time.
  5. Store the current measurement for the next calculation.

In Arduino-style C++, the essential calculation looks like this:

float dt = (currentTime - previousTime) / 1000.0f;

float velocity =
    (currentPosition - previousPosition) / dt;

If position is measured in metres, velocity will be measured in metres per second.

An important consideration is that the measurement interval must be accurate. We should calculate the actual elapsed time rather than assume every sensor measurement takes exactly the same duration.

Step 4: Calculating acceleration and jerk

Once velocity is available, we can calculate acceleration using the same technique.

float acceleration =
    (currentVelocity - previousVelocity) / dt;

We can also calculate jerk:

float jerk =
    (currentAcceleration - previousAcceleration) / dt;

The units are:

MeasurementUnits
PositionMetres
Velocitym/s
Accelerationm/s²
Jerkm/s³

This is where our project becomes particularly interesting.

Even when the measured object remains stationary, the calculated acceleration and jerk might fluctuate substantially.

Why?

Because real sensors produce measurement noise.

Differentiation amplifies this noise. Calculating the second and third derivatives can make the problem progressively worse.

Simply differentiating raw sensor readings is therefore unlikely to produce satisfactory results.

Step 5: Filtering sensor measurements

To improve the output, we can apply a low-pass filter before differentiating the position measurements.

One simple approach is an exponential moving average:

filteredPosition =
    alpha * measuredPosition +
    (1.0f - alpha) * filteredPosition;

Here, alpha controls how strongly the filter responds to new measurements.

For example:

  • A small alpha produces smoother readings but introduces more delay.
  • A larger alpha responds more quickly but allows more noise through.

We could begin experimenting with an alpha value of 0.2 and adjust it based on the results.

A more advanced implementation could use a Savitzky–Golay filter, which fits a polynomial to a window of measurements and can estimate derivatives from that polynomial.

This could become an interesting experiment in its own right: comparing different numerical differentiation techniques and measuring their accuracy.

Filtering introduces trade-offs, particularly between responsiveness, noise reduction and delay.

Step 6: Building a live dashboard

The ESP32 includes Wi-Fi functionality, which means we can display measurements in a browser without connecting it to a computer.

We can create a small web server running directly on the ESP32.

The browser dashboard would contain four graphs:

GraphWhat it shows
PositionDistance from the sensor over time
VelocityHow quickly the object is moving
AccelerationHow quickly the velocity changes
JerkHow quickly acceleration changes

A practical implementation could use a lightweight HTML page, JavaScript and a plotting library such as Chart.js.

The ESP32 could publish measurement data through a JSON endpoint or WebSocket connection.

For example, the microcontroller might provide the following data:

{
  "position": 0.45,
  "velocity": -0.50,
  "acceleration": -0.12,
  "jerk": 0.08
}

The values are illustrative.

The browser would then update its graphs as new measurements arrive.

We should also record timestamps and invalid measurements, rather than assuming every reading is successful.

A particularly useful feature would be the ability to export measurements as a CSV file for later analysis in Excel or Python.

Step 7: Experiments to perform

With the hardware and software operating, we can conduct several experiments.

Experiment A: Constant position

Hold an object stationary in front of the sensor.

Its velocity and acceleration should ideally be close to zero.

Any remaining variation helps us understand the effects of measurement noise.

Experiment B: Approximately constant velocity

Move an object steadily towards the sensor.

Position should change approximately linearly, velocity should remain reasonably constant and acceleration should be close to zero.

Experiment C: Acceleration and deceleration

Begin moving an object slowly, increase its speed and then bring it to a stop.

We should observe acceleration during the speed increase and acceleration in the opposite direction during deceleration.

Experiment D: Sudden changes in movement

Move an object abruptly and compare the results with those obtained during smooth movement.

This helps demonstrate jerk and the sensitivity of higher-order derivatives to both genuine motion and measurement noise.

These experiments demonstrate why sensor processing and mathematical differentiation are closely linked.


Project 2: Building an Intelligent Motor Controller

Our second project takes the mathematics further.

Instead of simply observing movement, we will use differentiation to regulate it.

The objective is to construct a motor-driven mechanism capable of following a target movement while continuously monitoring and correcting its performance.

This introduces us to closed-loop control and one of the most widely used techniques in engineering: the PID controller.

What are we building?

Imagine connecting a motor to a rotating arm.

We tell the ESP32 to rotate the arm through 90 degrees.

A simple motor controller might apply power for a predetermined period and then stop.

Unfortunately, this approach is unreliable.

Motor speed changes with battery voltage, load, mechanical resistance and numerous other factors.

If we need repeatable movement, we require feedback.

Our motor will therefore incorporate a rotary encoder, enabling the ESP32 to measure how far the shaft has rotated.

By differentiating its angular position, we can calculate angular velocity and acceleration.

The ESP32 can then adjust motor power to reduce the difference between the required and actual position.

Hardware requirements

ComponentPurpose
ESP32 DevKitMain controller
6V geared DC motor with quadrature encoderMovement and position feedback
TB6612FNG motor-driver breakoutControls motor power and direction
Regulated 6V power supplyMotor power
Appropriate connectors and wiringElectrical connections
Small rotating arm or pointerVisual demonstration
Emergency stop or accessible motor-power disconnectSafe testing
OLED display (optional)Shows target and actual position

For a small experimental motor, the TB6612FNG is a suitable choice, provided the motor's operating and stall-current requirements are compatible with the driver's ratings.

It is not suitable for every 6V motor. We must verify the motor's datasheet before connecting it.

Step 1: Connecting the motor driver

A practical pin arrangement is:

TB6612FNG connectionESP32 or power supply
VCCESP32 3.3V
GNDESP32 GND and motor supply negative
VMRegulated 6V motor supply positive
AIN1GPIO 18
AIN2GPIO 19
PWMAGPIO 25
STBYGPIO 23
AO1 and AO2Motor terminals

The encoder can use:

Encoder connectionESP32
Channel AGPIO 32
Channel BGPIO 33
Encoder groundGND
Encoder supplyManufacturer-specified voltage

The encoder signals must be compatible with the ESP32's 3.3V inputs. If the encoder produces 5V signals, suitable level shifting is required.

The ESP32 can be powered through USB during initial development, while the motor receives power from a separate regulated supply.

Both circuits must share a common ground.

We must not attempt to drive the motor directly from the ESP32 GPIO pins.

We should also include suitable motor-supply decoupling, protection against excessive current and a way to remove motor power immediately.

Step 2: Reading the rotary encoder

A quadrature encoder produces two digital signals, normally called A and B.

As the motor rotates, these signals transition between high and low states.

The relative timing of their transitions allows us to determine rotational direction.

By counting the transitions, we can estimate shaft position.

For example, suppose the gearbox's output shaft produces 1,200 encoder counts per revolution using our selected counting method.

Each count represents:

360 / 1200 = 0.3 degrees

If the shaft moves through 300 counts, its estimated angular displacement is:

300 × 0.3 = 90 degrees

The actual number of counts per output-shaft revolution depends on the encoder, gearbox ratio and counting method.

This value must come from the motor specifications or be established through calibration.

We can count encoder transitions using GPIO interrupts. For higher-speed applications, the ESP32's hardware pulse-counting facilities offer a more robust approach.

Step 3: Calculating rotational velocity

Our encoder gives angular position.

Differentiation converts this position into angular velocity.

The discrete calculation is:

Angular velocity = Change in angle / Change in time

If our motor rotates 18 degrees in 0.2 seconds:

Angular velocity = 18 / 0.2 = 90 degrees per second

We can convert this into revolutions per minute if required:

RPM = Angular velocity × 60 / 360

Therefore:

RPM = 15

By calculating velocity continuously, our system gains information that a basic position-only controller would not have.

For example, the motor may currently be 10 degrees away from its desired position but moving towards it rapidly.

If we only consider positional error, the controller could continue applying excessive power and overshoot the target.

Velocity feedback allows us to anticipate that movement and reduce the control effort.

Step 4: Introducing PID control

PID stands for Proportional, Integral and Derivative.

It is a feedback-control technique widely used in industrial equipment, robotics and automation.

A PID controller calculates an output based on three contributions.

Proportional control (P)

This responds to the difference between the desired position and the measured position.

A larger position error produces a stronger corrective response.

Integral control (I)

This accumulates the position error over time.

It helps correct persistent errors that proportional control alone cannot eliminate.

Derivative control (D)

This considers how rapidly the error changes.

It can improve damping and help reduce overshoot.

The conventional PID equation is:

Control output = Kp × error + Ki × integral(error) + Kd × derivative(error)

Here, Kp, Ki and Kd are adjustable controller gains.

For a stationary position target, the derivative of the position error is effectively the negative of the measured angular velocity.

Consequently, the derivative term can act as a braking influence when the motor approaches its destination.

This is a particularly good demonstration of why differentiation matters in control engineering.

Step 5: Programming the control loop

We can organise the ESP32 software around a fixed-period control loop.

A 20 ms loop period, equivalent to 50 control updates per second, provides a reasonable starting point for a small experimental mechanism.

The exact frequency should be selected based on the motor dynamics and encoder resolution.

Conceptually, the program would perform these operations:

1. Read the encoder count.

2. Calculate the motor's angular position.

3. Differentiate position to estimate velocity.

4. Filter the velocity measurement.

5. Calculate acceleration for monitoring.

6. Calculate the difference between target
   position and measured position.

7. Update the PID controller.

8. Limit the requested motor power.

9. Apply direction and PWM to the driver.

10. Repeat at the next control interval.

The PWM output controls the average voltage applied to the motor through the driver.

With the current Arduino-ESP32 API, PWM setup can use functions such as ledcAttach() and ledcWrite().

The controller should impose limits on output, accumulated integral error and the allowed movement range.

A complete implementation also requires an explicit stop state, encoder validation and a response to abnormal operating conditions.

Step 6: Testing and tuning the controller

Before attaching a moving arm or external load, we should test the motor without a mechanical obstruction.

The first tests should verify that the encoder reports the correct direction and that positive controller output moves the motor towards a positive target.

If the feedback sign is incorrect, a closed-loop controller can drive the motor away from its target instead of correcting the error.

After confirming the direction, we can begin tuning the controller.

A practical initial approach is:

First: Proportional control

Set Ki and Kd to zero.

Gradually increase Kp until the motor responds to a position command.

Observe how accurately it approaches the target and whether it oscillates.

Second: Derivative control

Introduce a small derivative gain.

Observe whether this reduces overshoot and improves stability.

Third: Integral control

Introduce integral action only when necessary to correct persistent steady-state errors.

Excessive integral action can lead to oscillation and a phenomenon called integral windup.

Initially, all tests should use low speeds, restricted travel and a mechanism that cannot cause injury.

Step 7: Adding controlled acceleration

We can make the motor controller more sophisticated by limiting how rapidly its commanded velocity changes.

Rather than asking the motor to move instantly towards a new position, we generate a reference trajectory.

For example, the motor could:

  1. Begin from rest.
  2. Accelerate smoothly.
  3. Move at a controlled speed.
  4. Decelerate as it approaches the target.
  5. Stop at the required position.

A trapezoidal velocity profile provides a useful starting point.

For even smoother movement, we could introduce a jerk-limited trajectory, sometimes called an S-curve profile.

This is where the concepts from our first project become directly useful.

We are no longer merely calculating velocity, acceleration and jerk.

We are actively managing how they change.

Step 8: Adding a web dashboard

As with the motion analyser, the ESP32 can host a browser-based dashboard.

For the motor controller, useful measurements would include:

ParameterPurpose
Target angleRequested position
Actual angleMeasured position
Position errorDifference between target and actual
Angular velocityMeasured motor speed
Angular accelerationChange in speed
PWM commandController output
Controller gainsAdjustable Kp, Ki and Kd

A graph showing the requested and actual positions on the same axes would be particularly useful.

We could command the motor to rotate through 90 degrees and then examine how closely the response matches the requested movement.

This provides a practical way to study settling time, overshoot, steady-state error and controller stability.

Changing the controller gains would produce visible differences in the response.

For safety, the motor-control loop should run locally on the ESP32. Wi-Fi communication should be used for monitoring and sending supervised commands, not as the timing mechanism for the control loop.


Combining the Two Projects

Although these projects work independently, combining them creates some interesting possibilities.

Imagine using the VL53L0X distance sensor to detect a moving object.

Our motion analyser could estimate the object's position and velocity.

We could then instruct the motor controller to move a mechanical pointer to follow that object.

The system would contain two separate feedback processes.

The sensing system:

Distance sensor → Position measurements → Numerical differentiation → Estimated motion

The control system:

Target position → Controller → Motor driver → Motor → Encoder → Feedback

By connecting the two systems, we can construct a basic tracking mechanism.

The system could respond not only to where an object is located but also to how quickly it is moving.

For example, we might use velocity estimates to compensate for the delay between detecting movement and physically adjusting the motor.

An experimental feed-forward term could command additional motor movement based on predicted target motion.

However, prediction will only be useful if the sensor measurements are sufficiently accurate and the mechanical system can respond quickly enough.

The VL53L0X is a reasonable sensor for demonstrating slow movements, but a more capable sensing system would be required for demanding high-speed tracking.


Taking the Projects Further

Once the basic hardware works, there are several opportunities for more advanced investigations.

Comparing numerical differentiation algorithms

We could compare forward differences, central differences and polynomial-based derivative estimation.

By applying known movements, we could evaluate:

  • Measurement error
  • Sensitivity to noise
  • Computational requirements
  • Filtering delay
  • Accuracy of velocity and acceleration estimates

This would establish how much confidence we should place in the calculated derivatives.

Comparing feedback-control strategies

The motor controller could provide an experimental platform for comparing proportional, PI, PD and PID control.

We could use repeated step-response experiments and record performance metrics.

More advanced implementations could investigate cascaded position and velocity control loops, feed-forward compensation and model-based control.

Investigating mechanical disturbances

Once we have a safe test fixture, we could introduce controlled changes in mechanical load.

We could investigate how quickly the controller responds and how effectively it maintains its position.

With an additional current sensor, we could also monitor motor current and relate electrical input to mechanical behaviour.

Adding data analysis and prediction

Measurements could be logged and processed using Python.

This would allow more sophisticated filtering, statistical analysis and system identification.

For example, we could estimate a simplified mathematical model of the motor from recorded input and output data.

Eventually, the controller could use that model to predict how its mechanical system will respond to a commanded movement.


Suggested Development Plan

Trying to build every feature immediately would make the projects unnecessarily difficult to debug.

A staged approach is more effective.

StageMotion analyserMotor controller
1Connect and test the distance sensorTest the motor and driver
2Record timestamped distance measurementsRead and calibrate encoder counts
3Calculate velocityCalculate angular position and velocity
4Calculate acceleration and jerkImplement proportional position control
5Add filteringIntroduce derivative damping and PID
6Build a web dashboardAdd motion limits and a web dashboard
7Validate results against known movementsMeasure step-response performance
8Compare differentiation techniquesDevelop smooth motion profiles
9Export data for analysisRecord controller performance
10Integrate with motor projectIntegrate with distance-sensing project

We should complete and validate the core hardware functionality before introducing more advanced features.

This reduces the risk of confusing sensor problems, programming errors and mathematical issues.


What Will These Projects Teach Us?

The greatest advantage of these two experiments is that they connect several disciplines.

The motion analyser explores how mathematical differentiation can be implemented using real sensor measurements.

It also exposes the limitations of numerical methods, including noise amplification, finite sampling rates and filtering delays.

The motor controller then demonstrates why those derivative estimates matter.

Rather than simply showing mathematical results on a screen, differentiation becomes part of a system that actively regulates physical movement.

Together, the projects introduce practical concepts from:

  • Calculus and numerical mathematics
  • Embedded software engineering
  • Digital signal processing
  • Measurement and instrumentation
  • Feedback-control theory
  • Electronics and motor control
  • Real-time monitoring and data analysis

They also offer opportunities to develop progressively more advanced experiments without replacing the entire platform.

Conclusion

Differentiation can sometimes seem abstract when presented entirely through equations.

However, an ESP32 allows us to observe the mathematics directly.

By connecting a distance sensor, we can measure movement and calculate its velocity, acceleration and jerk.

By adding a motor and encoder, we can use those mathematical principles to influence how a physical system behaves.

The first project turns differentiation into something we can measure.

The second turns it into something we can control.

And by combining them, we can begin developing a system capable of measuring motion, predicting how it may change and adjusting its behaviour accordingly.

That is a useful demonstration of the relationship between mathematics, electronics and modern control engineering.

Technical note: The wiring arrangements and code extracts in this guide are development examples, not a fully tested or compiled firmware package. Hardware specifications, encoder counts, control gains and safety limits must be verified for the particular components selected before powered operation.

← All articles

Related articles