Part 3 of the ESP32 Calculus and Control Engineering Series
Learn how to control a DC motor precisely using an ESP32, a rotary encoder, numerical differentiation and closed-loop PID feedback.
Introduction
In Part 2, we built an ESP32 motion analyser capable of measuring distance and calculating velocity, acceleration and jerk.
That project demonstrated how differentiation could be applied to real-world sensor measurements.
Now we are going to take the mathematics one step further.
Instead of simply measuring movement, we will use differentiation to control it.
Our project is an intelligent motor controller that can rotate a motor shaft to a requested position, measure its actual movement, calculate how quickly it is rotating and automatically adjust motor power to reduce positional errors.
We will achieve this using a technique called PID control.
PID stands for Proportional, Integral and Derivative. It is one of the most widely used control techniques in engineering.
The finished project will include a web dashboard, so we can command the motor to move to different positions and watch how the control system responds.
We will also implement a simple acceleration-limited motion profile, allowing the motor's commanded position to change progressively rather than jumping instantly to its destination.
Along the way, we will investigate how feedback, numerical differentiation and control theory work together.
1. What Are We Building?
Imagine a small motor connected to a pointer.
We want the pointer to move through 90 degrees and stop at that position.
Simply applying electrical power for a predetermined duration would not provide reliable positioning.
The result would depend on several factors, including supply voltage, friction, mechanical load and motor speed.
Instead, we will use a motor fitted with a rotary encoder.
The encoder measures the shaft's rotation.
The ESP32 continuously compares the actual position with the requested position.
If the motor has not moved far enough, the ESP32 applies power.
As the motor approaches the requested angle, the controller uses position and velocity feedback to reduce the control output.
Our system will work approximately as follows:
Requested Angle
|
v
Motion Profile
|
v
+----------------+
| PID Controller |
+----------------+
|
PWM Output
|
v
+----------------+
| Motor Driver |
+----------------+
|
v
+----------------+
| DC Gearmotor |
+----------------+
|
v
Rotary Encoder
|
v
Measured Position
|
Differentiation
|
v
Measured Velocity
|
+------> PID Feedback
The key difference from a basic motor circuit is that the ESP32 constantly monitors the result of its own commands.
This is called closed-loop control.
2. Choosing the Hardware
For this experiment, I have selected a specific motor and driver combination rather than an unspecified motor kit.
This is important because motor-driver selection depends on the motor's voltage and current requirements.
Components
| Component | Specification | Purpose |
|---|---|---|
| ESP32 DevKit | Original ESP32, 3.3V GPIO | Main controller |
| Pololu motor #5134 | 50:1 MP 6V with quadrature encoder | Controlled movement |
| Pololu TB6612FNG carrier #713 | 1A continuous per channel | Motor driver |
| Pololu encoder cable #4763 | Six-pin JST SH, unterminated end | Motor and encoder connections |
| Regulated power supply | 6V, approximately 1A capacity | Motor power |
| USB supply | Suitable ESP32 USB supply | Controller power |
| Small motor bracket and shaft hub | Suitable for 3mm D-shaft | Mechanical mounting |
| Motor-power isolation switch | Rated for the supply and motor current | Physical disconnect |
| Breadboard, connectors and jumper wires | 3.3V-compatible wiring | Prototyping |
The Pololu 50:1 medium-power motor has the following manufacturer specifications:
| Parameter | Value |
|---|---|
| Nominal voltage | 6V |
| Gear ratio | 51.45:1 |
| No-load output speed | 420 RPM |
| Typical no-load current | 70 mA |
| Theoretical stall current | 670 mA |
| Encoder resolution | 12 counts per motor-shaft revolution, with 4× decoding |
The TB6612FNG carrier supports a recommended motor supply of 4.5–13.5V, with a nominal continuous current rating of 1A per channel, subject to thermal conditions.
Our selected motor is within those electrical limits, although a stalled motor must never be left energised indefinitely.
A 6V supply with adjustable current limiting is particularly useful for initial development.
Safety: This is a low-power educational mechanism. Keep the shaft unloaded initially. Do not attach a heavy arm, cutting tool or any mechanism capable of trapping fingers. Use a physical motor-power disconnect; a software stop button alone is not an emergency stop.
3. Understanding the Rotary Encoder
A conventional DC motor provides no direct information about how far its shaft has rotated.
A rotary encoder solves this problem.
Our selected motor includes a two-channel incremental quadrature encoder mounted on its motor shaft, before the gearbox.
The channels are called A and B.
As the motor rotates, they produce digital signals that change between high and low states.
The signals are offset in phase, so the ESP32 can determine both movement and direction.
A simplified quadrature sequence is:
Channel A: __----____----____
Channel B: ____----____----__
Time: ----------------->
The exact sequence depends on rotation direction.
By detecting both rising and falling edges on both channels, we obtain four-count quadrature decoding.
The Pololu encoder produces 12 counts per revolution of the motor shaft with this decoding method.
However, our output shaft rotates much more slowly because of the gearbox.
The manufacturer specifies a reduction ratio of 51.45:1.
Therefore, the approximate output-shaft encoder resolution is:
12 × 51.45 = 617.4 counts per revolution
This gives an angular resolution of approximately:
360 / 617.4 = 0.583 degrees per count.
This does not imply that the mechanism has 0.583-degree absolute positioning accuracy. Backlash, encoder quantisation, electrical noise and other errors affect achievable performance.
The controller also measures relative position only. It does not know the shaft's absolute angle when power is applied.
For this project, we will define the starting position as zero degrees.
A more advanced build could incorporate a home-position switch.
4. Connecting the Motor Driver to the ESP32
We will use one motor channel of the TB6612FNG driver.
The second channel is not required.
Motor-driver wiring
| TB6612FNG pin | Connection |
|---|---|
| VCC | ESP32 3.3V |
| GND | Common ground |
| VMOT | External regulated 6V supply |
| AIN1 | ESP32 GPIO 18 |
| AIN2 | ESP32 GPIO 19 |
| PWMA | ESP32 GPIO 25 |
| STBY | ESP32 GPIO 23 |
| AO1 | Motor M1 |
| AO2 | Motor M2 |
Leave the unused B-channel motor outputs disconnected. Its control inputs should be held low or otherwise configured according to the carrier documentation rather than left floating.
The ESP32 and motor supply must share a common ground.
The 6V supply must not be connected directly to the ESP32's 3.3V pin.
Connecting the encoder
Using Pololu's colour-coded six-pin cable #4763:
| Wire colour | Function | Connection |
|---|---|---|
| Green | Encoder GND | ESP32 GND |
| White | Encoder channel B | GPIO 33 |
| Yellow | Encoder channel A | GPIO 32 |
| Blue | Encoder supply | ESP32 3.3V |
| Black | Motor M2 | TB6612FNG AO2 |
| Red | Motor M1 | TB6612FNG AO1 |
These colours apply to the specified Pololu cable, not necessarily to third-party cables.
Powering the encoder at 3.3V ensures that its output pull-ups are compatible with the ESP32 GPIO inputs.
Simplified electrical layout
ESP32
+----------------+
| |
GPIO 18 -----+ AIN1 |
GPIO 19 -----+ AIN2 |
GPIO 25 -----+ PWMA |
GPIO 23 -----+ STBY |
| |
GPIO 32 <----+ Encoder A |
GPIO 33 <----+ Encoder B |
| |
3.3V --------+ Logic VCC |
GND ---------+ Common GND |
+----------------+
|
v
+----------------+
| TB6612FNG |
| Motor Driver |
| |
6V Supply -->| VMOT |
GND -------->| GND |
| AO1 AO2 |
+--+---------+---+
| |
v v
+---------+
| DC Motor|
+---------+
|
Gearbox Shaft
|
Encoder Signals
|
ESP32
This is a functional overview, not a full electrical schematic. The pin tables define the connections.
We should add appropriate supply decoupling near the motor driver and use suitable wiring for motor current.
Do not route motor current through unsuitable breadboard tracks or delicate signal wires.
Adding a stop button
We will also connect a normally open pushbutton between GPIO 27 and ground.
The ESP32 will configure GPIO 27 as INPUT_PULLUP.
Pressing this button will request a software stop and latch a fault.
This is not a safety-rated emergency stop. A separate, accessible switch must physically isolate the motor supply.
5. Understanding the Mathematics
Before writing our firmware, we need to understand the control equations.
Position
The encoder produces a count.
We convert this into an angular position:
Angle = Encoder count × 360 / Counts per revolution
For example, approximately 154.35 counts represents 90 degrees.
In practice, the encoder count is an integer and the conversion produces an estimated angle.
Angular velocity
Differentiation converts angular position into angular velocity.
The formula is:
ω = dθ/dt
For a sampled system:
ω ≈ (θ₂ − θ₁) / Δt
Suppose the shaft moves from 30 to 42 degrees in 0.2 seconds.
The angular velocity is:
(42 − 30) / 0.2 = 60 degrees per second.
Angular acceleration
Acceleration is the rate of change of velocity.
α = dω/dt
If angular velocity increases from 40 to 70 degrees per second over 0.5 seconds:
Angular acceleration = (70 − 40) / 0.5
Angular acceleration = 60 degrees per second squared.
Our controller will use filtered velocity feedback, while acceleration will primarily be recorded for analysis.
The distinction is important: calculating acceleration does not automatically make a controller predictive. The acceleration estimate must be incorporated into a prediction or control strategy for that purpose.
6. Introducing PID Control
The central principle of closed-loop control is error correction.
We define the position error as:
Error = Requested position − Actual position
If the requested angle is 90 degrees and the measured angle is 65 degrees:
Error = 25 degrees.
The controller must apply motor power to reduce that error.
PID control provides three mechanisms.
Proportional control
The proportional term is:
P = Kp × Error
A larger error produces a stronger response.
As the motor approaches the destination, the proportional contribution decreases.
Integral control
The integral term accumulates error over time:
I = Ki × ∫Error dt
It is useful for overcoming persistent steady-state errors.
However, excessive integral action can produce overshoot and oscillation.
We will therefore start with the integral gain disabled during initial testing.
Derivative control
The derivative term responds to how quickly the error changes:
D = Kd × d(Error)/dt
When the target is stationary, the derivative of the error is the negative of measured angular velocity.
This allows us to use velocity feedback directly.
The motor can therefore begin reducing its control effort before it reaches the target, rather than waiting until it has already overshot.
For our implementation, the control equation is:
Output = Kp × Error + Ki × Accumulated Error − Kd × Measured Velocity
Using derivative-on-measurement rather than directly differentiating a suddenly changing target helps avoid a large derivative impulse when the commanded angle changes.
7. Adding Smooth Motion Profiles
A basic PID controller can respond to a requested angle immediately.
However, asking a motor to move instantly from 0 to 90 degrees creates a large initial position error.
The controller may attempt to accelerate the motor aggressively.
Instead, we will generate an intermediate reference position that moves progressively towards the requested destination.
The reference trajectory will limit commanded velocity and acceleration.
For example:
- Maximum reference speed: 75 degrees per second.
- Maximum reference acceleration: 150 degrees per second squared.
- Permitted target positions: 0–180 degrees.
These are initial software settings, not guaranteed physical performance limits.
Our simple trajectory generator estimates the speed at which it must begin slowing down as it approaches the target.
The underlying relationship is:
v² = 2as
Where:
- v represents speed.
- a represents acceleration magnitude.
- s represents remaining distance.
Rearranging:
v = √(2as)
This provides an estimate of the speed that would allow the motion profile to stop within the remaining distance, assuming approximately constant deceleration.
The motor then follows this changing reference rather than responding to a single sudden position command.
This produces a basic acceleration-limited trapezoidal-style trajectory.
A later improvement would be to introduce jerk limits and generate a true S-curve motion profile.
8. Developing the ESP32 Firmware
We will now combine the different elements into one Arduino program.
The program will:
- Count quadrature encoder transitions.
- Calculate shaft position and filtered velocity.
- Generate an acceleration-limited position reference.
- Calculate PID output.
- Drive the motor through PWM.
- Apply software travel limits.
- Stop if feedback is lost while significant power is commanded.
- Provide a standalone Wi-Fi dashboard.
The motor-control task will run separately from the web interface using FreeRTOS, which is included with the ESP32 Arduino environment.
This reduces the extent to which browser requests interfere with control timing.
For this example, use Arduino-ESP32 3.x or a compatible later version. Earlier releases use different LEDC PWM functions.
Complete example sketch
Create a new Arduino sketch called ESP32_PID_Motor_Controller.
#include <Arduino.h>
#include <WiFi.h>
#include <WebServer.h>
#include <math.h>
// Hardware pins
constexpr int PIN_IN1 = 18;
constexpr int PIN_IN2 = 19;
constexpr int PIN_PWM = 25;
constexpr int PIN_STBY = 23;
constexpr int PIN_ENC_A = 32;
constexpr int PIN_ENC_B = 33;
constexpr int PIN_STOP = 27;
// Motor and encoder
constexpr float GEAR_RATIO = 51.45f;
constexpr float MOTOR_CPR = 12.0f;
constexpr float OUTPUT_CPR =
MOTOR_CPR * GEAR_RATIO;
// Set to -1 if encoder direction is reversed
constexpr float ENCODER_SIGN = 1.0f;
// Motion profile settings
constexpr float MAX_SPEED = 75.0f;
constexpr float MAX_ACCEL = 150.0f;
// Initial controller gains - tune experimentally
constexpr float KP = 2.0f;
constexpr float KI = 0.0f;
constexpr float KD = 0.20f;
// PWM restrictions
constexpr int PWM_LIMIT = 100;
constexpr int PWM_FREQUENCY = 20000;
constexpr int PWM_RESOLUTION = 8;
// Shared state
struct MotorState {
float goal = 0;
float reference = 0;
float angle = 0;
float velocity = 0;
float acceleration = 0;
float error = 0;
int pwm = 0;
int fault = 0;
bool enabled = false;
};
MotorState state;
portMUX_TYPE stateMux =
portMUX_INITIALIZER_UNLOCKED;
portMUX_TYPE encoderMux =
portMUX_INITIALIZER_UNLOCKED;
volatile int32_t encoderCount = 0;
volatile uint8_t previousAB = 0;
WebServer server(80);
// Access point
const char* WIFI_NAME = "ESP32-MotorLab";
const char* WIFI_PASS = "MotorLab123";
// Quadrature transition lookup table
const int8_t QUAD_TABLE[16] = {
0, -1, 1, 0,
1, 0, 0, -1,
-1, 0, 0, 1,
0, 1, -1, 0
};
// Quadrature encoder interrupt
void IRAM_ATTR encoderISR() {
portENTER_CRITICAL_ISR(&encoderMux);
uint8_t ab =
(digitalRead(PIN_ENC_A) << 1) |
digitalRead(PIN_ENC_B);
uint8_t index =
(previousAB << 2) | ab;
encoderCount += QUAD_TABLE[index];
previousAB = ab;
portEXIT_CRITICAL_ISR(&encoderMux);
}
// Obtain an atomic encoder count
int32_t getEncoderCount() {
portENTER_CRITICAL(&encoderMux);
int32_t count = encoderCount;
portEXIT_CRITICAL(&encoderMux);
return count;
}
// Copy telemetry safely
MotorState getState() {
MotorState snapshot;
portENTER_CRITICAL(&stateMux);
snapshot = state;
portEXIT_CRITICAL(&stateMux);
return snapshot;
}
// Latch a controller fault
void latchFault(int code) {
portENTER_CRITICAL(&stateMux);
if (state.fault == 0) {
state.fault = code;
}
state.enabled = false;
portEXIT_CRITICAL(&stateMux);
}
// Disable the motor driver
void motorOff() {
ledcWrite(PIN_PWM, 0);
digitalWrite(PIN_STBY, LOW);
}
// Apply signed PWM
void driveMotor(int command) {
command = constrain(
command, -PWM_LIMIT, PWM_LIMIT
);
if (command == 0) {
motorOff();
return;
}
// Remove PWM before direction changes
ledcWrite(PIN_PWM, 0);
digitalWrite(PIN_IN1,
command > 0 ? HIGH : LOW);
digitalWrite(PIN_IN2,
command > 0 ? LOW : HIGH);
digitalWrite(PIN_STBY, HIGH);
ledcWrite(PIN_PWM, abs(command));
}
// Dedicated motor-control task
void controlTask(void* parameter) {
TickType_t wake = xTaskGetTickCount();
uint32_t previousUs = micros();
float previousAngle = 0;
float previousVelocity = 0;
float velocity = 0;
float acceleration = 0;
float reference = 0;
float referenceVelocity = 0;
float integral = 0;
int32_t previousProgressCount = 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) {
latchFault(3);
dt = 0.02f;
}
int32_t count = getEncoderCount();
float angle =
ENCODER_SIGN *
float(count) * 360.0f / OUTPUT_CPR;
float rawVelocity =
(angle - previousAngle) / dt;
previousAngle = angle;
velocity =
0.25f * rawVelocity +
0.75f * velocity;
float rawAcceleration =
(velocity - previousVelocity) / dt;
previousVelocity = velocity;
acceleration =
0.25f * rawAcceleration +
0.75f * acceleration;
// Software stop input
if (digitalRead(PIN_STOP) == LOW) {
latchFault(1);
}
// Relative travel protection
if (angle < -10.0f || angle > 190.0f) {
latchFault(2);
}
MotorState snapshot = getState();
float error = 0;
int command = 0;
if (!snapshot.enabled ||
snapshot.fault != 0) {
motorOff();
reference = angle;
referenceVelocity = 0;
integral = 0;
previousProgressCount = count;
lastProgressMs = millis();
} else {
float remaining =
snapshot.goal - reference;
float direction =
remaining >= 0 ? 1.0f : -1.0f;
float stoppingSpeed =
sqrtf(2.0f * MAX_ACCEL *
fabsf(remaining));
float desiredVelocity =
direction *
fminf(MAX_SPEED, stoppingSpeed);
float deltaVelocity = constrain(
desiredVelocity - referenceVelocity,
-MAX_ACCEL * dt,
MAX_ACCEL * dt
);
referenceVelocity += deltaVelocity;
float nextReference =
reference + referenceVelocity * dt;
// Prevent reference overshoot
if ((remaining >= 0 &&
nextReference > snapshot.goal) ||
(remaining < 0 &&
nextReference < snapshot.goal)) {
reference = snapshot.goal;
referenceVelocity = 0;
} else {
reference = nextReference;
}
error = reference - angle;
// Integral with simple anti-windup
float proposedIntegral =
constrain(
integral + error * dt,
-80.0f,
80.0f
);
float trialOutput =
KP * error +
KI * proposedIntegral -
KD * velocity;
if (fabsf(trialOutput) < PWM_LIMIT) {
integral = proposedIntegral;
}
float output =
KP * error +
KI * integral -
KD * velocity;
output = constrain(
output,
-float(PWM_LIMIT),
float(PWM_LIMIT)
);
command = int(roundf(output));
// Stop within a small tolerance
if (fabsf(error) < 1.0f &&
fabsf(velocity) < 3.0f) {
command = 0;
}
// Detect lack of encoder progress
if (abs(command) >= 70) {
if (labs(
long(count - previousProgressCount)
) >= 3) {
previousProgressCount = count;
lastProgressMs = millis();
} else if (
millis() - lastProgressMs > 700
) {
latchFault(4);
command = 0;
}
} else {
previousProgressCount = count;
lastProgressMs = millis();
}
MotorState latest = getState();
if (latest.enabled &&
latest.fault == 0) {
driveMotor(command);
} else {
command = 0;
motorOff();
}
}
portENTER_CRITICAL(&stateMux);
state.angle = angle;
state.velocity = velocity;
state.acceleration = acceleration;
state.reference = reference;
state.error = error;
state.pwm = command;
portEXIT_CRITICAL(&stateMux);
}
}
// Embedded 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 PID Motor Controller</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
background: #f1f4f8;
color: #202938;
}
main {
max-width: 850px;
margin: auto;
padding: 20px;
}
.card {
background: white;
padding: 18px;
margin-bottom: 14px;
border-radius: 12px;
}
.metrics {
display: grid;
grid-template-columns:
repeat(auto-fit, minmax(145px, 1fr));
gap: 10px;
}
.metric {
padding: 15px;
background: #f3f5f8;
border-radius: 8px;
}
.metric strong {
display: block;
font-size: 25px;
margin-top: 8px;
}
button {
padding: 12px 15px;
border: 0;
border-radius: 8px;
background: #2860c7;
color: white;
margin: 4px;
cursor: pointer;
}
.stop { background: #b52e2e; }
canvas {
width: 100%;
height: 200px;
}
</style>
</head>
<body>
<main>
<h1>ESP32 PID Motor Controller</h1>
<p id="status">Connecting...</p>
<div class="card">
<h3>Controls</h3>
<button onclick="send('/arm')">Enable</button>
<button onclick="move(0)">0°</button>
<button onclick="move(45)">45°</button>
<button onclick="move(90)">90°</button>
<button onclick="move(180)">180°</button>
<button class="stop"
onclick="send('/stop')">STOP</button>
<button onclick="send('/reset')">
Reset fault
</button>
</div>
<div class="card">
<div class="metrics">
<div class="metric">Actual angle
<strong id="angle">--</strong></div>
<div class="metric">Target angle
<strong id="goal">--</strong></div>
<div class="metric">Velocity
<strong id="velocity">--</strong></div>
<div class="metric">Error
<strong id="error">--</strong></div>
<div class="metric">PWM
<strong id="pwm">--</strong></div>
<div class="metric">Acceleration
<strong id="acceleration">--</strong></div>
</div>
</div>
<div class="card">
<h3>Position response</h3>
<p>Blue: actual position |
Orange: reference position</p>
<canvas id="chart"></canvas>
<button onclick="saveCSV()">Export CSV</button>
</div>
</main>
<script>
const samples = [];
async function send(path) {
const response = await fetch(path);
const text = await response.text();
if (!response.ok) {
alert(text);
}
}
function move(degrees) {
send('/move?d=' + degrees);
}
function draw() {
const canvas =
document.getElementById('chart');
const width = canvas.clientWidth;
const height = 200;
const ratio = devicePixelRatio || 1;
canvas.width = width * ratio;
canvas.height = height * ratio;
const ctx = canvas.getContext('2d');
ctx.scale(ratio, ratio);
ctx.strokeStyle = '#d4dae5';
ctx.beginPath();
for (let i = 0; i <= 4; i++) {
const y = 10 + i * 45;
ctx.moveTo(10, y);
ctx.lineTo(width - 10, y);
}
ctx.stroke();
if (samples.length < 2) return;
const series = [
['angle', '#2463eb'],
['reference', '#ed8d24']
];
series.forEach(([key, colour]) => {
ctx.beginPath();
ctx.strokeStyle = colour;
ctx.lineWidth = 2;
samples.forEach((sample, index) => {
const x =
index * width /
Math.max(1, samples.length - 1);
const y =
190 - sample[key] * 180 / 180;
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('Connection error');
}
const d = await response.json();
const faults = [
'OK',
'STOP input activated',
'Travel limit exceeded',
'Control timing fault',
'Encoder progress fault'
];
document.getElementById('status')
.textContent =
d.fault ? faults[d.fault] :
d.enabled ? 'Controller enabled' :
'Controller disabled';
for (const key of [
'angle', 'goal', 'velocity',
'error', 'acceleration'
]) {
document.getElementById(key)
.textContent = d[key].toFixed(2);
}
document.getElementById('pwm')
.textContent = d.pwm;
samples.push({
time: Date.now(),
...d
});
if (samples.length > 600) {
samples.shift();
}
draw();
} catch (error) {
document.getElementById('status')
.textContent = 'Connection lost';
}
}
function saveCSV() {
const headers = [
'time', 'angle', 'reference',
'goal', 'velocity', 'acceleration',
'error', 'pwm'
];
const rows = [
headers.join(','),
...samples.map(s =>
headers.map(k => s[k]).join(',')
)
];
const blob = new Blob(
[rows.join('\n')],
{type: 'text/csv'}
);
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = 'motor_response.csv';
link.click();
URL.revokeObjectURL(url);
}
setInterval(update, 200);
update();
</script>
</body>
</html>
)HTML";
// Return live telemetry
void handleData() {
MotorState s = getState();
char result[300];
snprintf(
result, sizeof(result),
"{\"angle\":%.3f,"
"\"goal\":%.3f,"
"\"reference\":%.3f,"
"\"velocity\":%.3f,"
"\"acceleration\":%.3f,"
"\"error\":%.3f,"
"\"pwm\":%d,"
"\"fault\":%d,"
"\"enabled\":%s}",
s.angle,
s.goal,
s.reference,
s.velocity,
s.acceleration,
s.error,
s.pwm,
s.fault,
s.enabled ? "true" : "false"
);
server.send(
200, "application/json", result
);
}
void handleArm() {
if (digitalRead(PIN_STOP) == LOW) {
server.send(
409, "text/plain", "STOP input active"
);
return;
}
bool success = false;
portENTER_CRITICAL(&stateMux);
if (state.fault == 0) {
state.goal = state.angle;
state.enabled = true;
success = true;
}
portEXIT_CRITICAL(&stateMux);
server.send(
success ? 200 : 409,
"text/plain",
success ? "Enabled" : "Clear fault first"
);
}
void handleMove() {
if (!server.hasArg("d")) {
server.send(
400, "text/plain", "Missing target"
);
return;
}
float target = server.arg("d").toFloat();
if (!isfinite(target) ||
target < 0 ||
target > 180) {
server.send(
400, "text/plain",
"Target must be 0 to 180"
);
return;
}
bool accepted = false;
portENTER_CRITICAL(&stateMux);
if (state.enabled &&
state.fault == 0) {
state.goal = target;
accepted = true;
}
portEXIT_CRITICAL(&stateMux);
server.send(
accepted ? 200 : 409,
"text/plain",
accepted ? "Target accepted" :
"Controller not enabled"
);
}
void handleStop() {
portENTER_CRITICAL(&stateMux);
state.enabled = false;
portEXIT_CRITICAL(&stateMux);
motorOff();
server.send(
200, "text/plain", "Stopped"
);
}
void handleReset() {
if (digitalRead(PIN_STOP) == LOW) {
server.send(
409, "text/plain",
"Release STOP input first"
);
return;
}
portENTER_CRITICAL(&stateMux);
state.fault = 0;
state.enabled = false;
state.goal = state.angle;
portEXIT_CRITICAL(&stateMux);
motorOff();
server.send(
200, "text/plain",
"Fault cleared - controller disabled"
);
}
void setup() {
Serial.begin(115200);
pinMode(PIN_IN1, OUTPUT);
pinMode(PIN_IN2, OUTPUT);
pinMode(PIN_STBY, OUTPUT);
pinMode(PIN_STOP, INPUT_PULLUP);
digitalWrite(PIN_STBY, LOW);
digitalWrite(PIN_IN1, LOW);
digitalWrite(PIN_IN2, LOW);
if (!ledcAttach(
PIN_PWM,
PWM_FREQUENCY,
PWM_RESOLUTION)) {
Serial.println("PWM setup failed");
while (true) delay(1000);
}
motorOff();
pinMode(PIN_ENC_A, INPUT_PULLUP);
pinMode(PIN_ENC_B, INPUT_PULLUP);
previousAB =
(digitalRead(PIN_ENC_A) << 1) |
digitalRead(PIN_ENC_B);
attachInterrupt(
digitalPinToInterrupt(PIN_ENC_A),
encoderISR, CHANGE
);
attachInterrupt(
digitalPinToInterrupt(PIN_ENC_B),
encoderISR, CHANGE
);
WiFi.mode(WIFI_AP);
WiFi.softAP(WIFI_NAME, WIFI_PASS);
server.on("/", HTTP_GET, []() {
server.send_P(
200, "text/html", PAGE
);
});
server.on("/data", HTTP_GET, handleData);
server.on("/arm", HTTP_GET, handleArm);
server.on("/move", HTTP_GET, handleMove);
server.on("/stop", HTTP_GET, handleStop);
server.on("/reset", HTTP_GET, handleReset);
server.begin();
xTaskCreatePinnedToCore(
controlTask,
"MotorControl",
4096,
nullptr,
3,
nullptr,
1
);
Serial.print("Dashboard: http://");
Serial.println(WiFi.softAPIP());
}
void loop() {
server.handleClient();
static uint32_t lastPrint = 0;
if (millis() - lastPrint >= 500) {
lastPrint = millis();
MotorState s = getState();
Serial.printf(
"Angle %.2f | Target %.2f | "
"Speed %.2f | PWM %d | Fault %d\n",
s.angle,
s.goal,
s.velocity,
s.pwm,
s.fault
);
}
delay(2);
}
Important notes about the firmware
This is a reference implementation for a lightweight experimental mechanism, not a certified motion controller.
The initial PID gains are deliberately conservative. They have not been tuned to an assembled motor and load, and the integral gain begins at zero.
The program has several protective behaviours, including a software stop input, relative-position boundaries, a control-loop timing check and basic missing-encoder-progress detection.
These are useful safeguards, but they cannot guarantee protection against every electrical, mechanical or software failure.
The 0–180 degree range is relative to the position at startup. It is not an absolute mechanical travel limit.
The control task runs with a nominal 20 ms period. The actual timing and responsiveness should be measured during testing.
Before enabling closed-loop control, we must independently verify that the motor's positive drive direction produces increasing encoder position. Otherwise, feedback may become positive rather than negative, causing uncontrolled movement.
The browser's CSV export records the values received by the browser, not every individual control-loop sample.
9. Uploading and Testing the Firmware
Install the Arduino IDE and the Espressif ESP32 board support package.
This sketch uses the standard ESP32 Arduino libraries:
- WiFi
- WebServer
- Arduino core functions
No third-party PID library is required because we have implemented the controller equations ourselves.
Initial power-up
For the first test, disconnect the external 6V motor power supply.
Keep the ESP32 powered through USB.
Upload the firmware and open the Serial Monitor at 115200 baud.
The ESP32 should initialise its GPIO connections, create its Wi-Fi network and start the web server.
With the motor supply disconnected, the motor cannot be driven.
Testing the encoder
Carefully rotate the motor's output shaft by hand, if the gearbox can be back-driven without excessive force. Do not force a gearbox that resists manual rotation.
Alternatively, use a separate low-power open-loop motor test to verify encoder counting before enabling the PID controller.
Observe the angular position reported in the Serial Monitor or dashboard.
Positive shaft movement should produce increasing measured angle when the encoder sign is correctly configured.
If the direction is opposite to the intended positive motor drive direction, change:
ENCODER_SIGN = 1.0f
to:
ENCODER_SIGN = -1.0f
in the firmware.
Do not enable the closed-loop controller until this direction relationship has been verified.
A short, low-power open-loop test on an unloaded and securely mounted motor is the safest way to establish the relationship between motor polarity and encoder direction.
Connecting motor power
Once the encoder and motor-direction checks pass, connect the regulated 6V motor supply.
Limit the available current during initial development where possible.
Use the physical disconnect switch to isolate motor power whenever wiring or mechanical adjustments are required.
Keep the shaft free of external loads for the first closed-loop tests.
10. Opening the Web Dashboard
The ESP32 creates its own Wi-Fi network.
Connect a phone or computer to:
Network: ESP32-MotorLab
Password: MotorLab123
Then open:
The dashboard should display the controller status and live measurements.
It includes buttons for requesting the following angular positions:
- 0 degrees
- 45 degrees
- 90 degrees
- 180 degrees
There are also controls for enabling the controller, stopping it and clearing faults.
The controller starts disabled.
Pressing Enable permits position commands, but does not itself request a movement away from the current position.
For the first closed-loop experiment, use the smallest practical movement and keep the motor unloaded.
The dashboard displays the actual and reference positions on a common graph.
This allows us to examine how closely the motor follows the motion profile.
For later experiments, we can export the measurements for analysis in Excel or Python.
Change the default Wi-Fi password before operating the device anywhere that other people might access the network. The web interface has no separate user authentication.
11. Experiment 1: Proportional Control
Our first control experiment will use proportional feedback only.
Set:
KP = 2.0
KI = 0.0
KD = 0.0
Recompile and upload the firmware.
After verifying motor direction, enable the controller and request a small position change.
Observe how the motor moves.
The proportional controller calculates:
Output = Kp × Error
When the positional error is large, the controller commands more power.
As the error decreases, the command decreases.
However, the motor may continue moving because of inertia.
It may overshoot or oscillate around its target.
The behaviour will depend on the selected proportional gain and the mechanical characteristics of the motor.
Gradually adjust Kp and repeat the experiment.
Record the results so that changes in controller performance can be compared.
12. Experiment 2: Adding Derivative Control
Now introduce a derivative gain:
KD = 0.20
This enables velocity feedback.
Our equation becomes:
Output = Kp × Error − Kd × Velocity
When the motor is moving rapidly towards the target, the derivative contribution opposes the movement.
This provides damping.
It may reduce overshoot and improve stability.
Repeat the same movement as Experiment 1.
Compare the results.
Useful measurements include:
| Performance measure | Meaning |
|---|---|
| Rise time | How quickly the motor approaches the target |
| Overshoot | How far it moves beyond the target |
| Settling time | How long it takes to remain near the target |
| Steady-state error | Remaining position error |
| PWM activity | Amount and variation of control effort |
Derivative feedback can also amplify measurement noise, so filtering the encoder-derived velocity is important.
The ideal gain depends on the actual motor and mechanical load.
There is no universally correct Kd value.
13. Experiment 3: Introducing Integral Control
The next experiment investigates integral action.
We can begin with a small value, for example:
KI = 0.02
The exact value is a tuning experiment, not a recommended universal setting.
Integral control accumulates the position error over time.
This helps correct situations where the motor settles slightly away from its target.
However, too much integral action can cause slow oscillations, excessive overshoot and integral windup.
Our firmware limits the accumulated integral value and restricts integration when the preliminary output is saturated.
This is a basic anti-windup strategy.
For more demanding systems, more sophisticated anti-windup schemes may be needed.
We should compare the final positional accuracy with and without the integral term.
A motor that achieves sufficient accuracy with PD control may not require integral action at all.
14. Experiment 4: Smooth Acceleration and Deceleration
We will now investigate how the reference trajectory influences motor movement.
The program contains two important parameters:
MAX_SPEED = 75.0f
MAX_ACCEL = 150.0f
The first limits the commanded reference velocity.
The second limits how rapidly the reference velocity changes.
Request a movement from 0 to 90 degrees.
The controller should attempt to follow a reference that accelerates, travels towards the target and then slows down.
On the dashboard, compare the reference position against the actual measured position.
If the motor follows successfully, both curves should have a similar shape.
If the actual position lags substantially behind, the controller may require further tuning.
We can experiment with lower reference speeds and accelerations before trying more demanding movements.
A key observation is that the controller is not directly commanding acceleration.
It is commanding motor power while attempting to follow a position reference whose movement is constrained by acceleration limits.
This distinction is central to understanding motion-control engineering.
15. Experiment 5: Disturbance Rejection
Once the unloaded motor responds reliably, we can investigate how the controller deals with changing mechanical conditions.
A suitable test might involve introducing a very small, controlled change in load using a designed fixture.
Do not hold or obstruct the rotating shaft with your fingers.
Observe how the measured position responds to the disturbance.
A well-tuned feedback controller should attempt to reduce the resulting position error.
However, the motor may not have sufficient torque to overcome every disturbance.
The firmware also includes basic detection of situations where significant PWM is commanded but the encoder shows little or no progress.
If this occurs, the controller disables motor output and reports a fault.
This feature reduces the risk of prolonged uncontrolled stalling, but it does not replace proper current limiting or physical protection.
For more advanced experiments, adding a motor-current sensor would allow us to investigate the relationship between torque demand, current and mechanical loading.
16. Analysing the Results
The web dashboard can export a CSV file containing:
| Field | Description |
|---|---|
| Time | Browser timestamp |
| Angle | Measured shaft position |
| Reference | Profile-generated position |
| Goal | Requested destination |
| Velocity | Estimated angular velocity |
| Acceleration | Estimated angular acceleration |
| Error | Position difference |
| PWM | Controller output |
The data can be imported into Excel or Python.
One of the most useful analyses is to plot actual and reference position against time.
We can then compare the results obtained with different PID gains.
We might also calculate maximum overshoot, mean absolute position error and settling time.
Example Python analysis
import pandas as pd
import matplotlib.pyplot as plt
data = pd.read_csv("motor_response.csv")
time_s = (
data["time"] - data["time"].iloc[0]
) / 1000.0
plt.plot(
time_s,
data["goal"],
label="Requested angle",
linestyle=":"
)
plt.plot(
time_s,
data["reference"],
label="Reference position"
)
plt.plot(
time_s,
data["angle"],
label="Actual position"
)
plt.xlabel("Time (seconds)")
plt.ylabel("Position (degrees)")
plt.title("ESP32 Motor Position Response")
plt.legend()
plt.grid(True)
plt.show()
This generates a graph showing the relationship between the requested target, the trajectory generated by the ESP32 and the position actually achieved by the motor.
The data collected through the browser is suitable for introductory analysis.
For detailed control-loop timing studies, the ESP32 should log every control cycle with microsecond timestamps, preferably through a non-blocking buffer.
17. Troubleshooting
During development, several problems may occur.
| Problem | Possible cause |
|---|---|
| Motor does not move | Check motor power, STBY, PWM and enable state |
| Motor moves in the wrong direction | Incorrect polarity or encoder sign |
| Motor accelerates away from target | Feedback direction is incorrect; isolate motor power |
| Motor oscillates | Excessive controller gains or mechanical effects |
| Motor stops short of target | Insufficient control effort, friction or steady-state error |
| Controller reports encoder fault | Missing pulses, excessive friction or motor unable to turn |
| Position changes unexpectedly | Electrical noise, encoder errors or loose wiring |
| ESP32 resets when motor starts | Power-supply disturbance or inadequate decoupling |
| Dashboard disconnects | Wi-Fi interference or ESP32 reset |
| Motor overheats | Excessive loading, stall conditions or poor control tuning |
Avoid treating software tuning as the solution to every problem.
For example, if the motor cannot move because its supply voltage collapses, increasing Kp will not fix the underlying electrical issue.
Likewise, if encoder direction is incorrect, changing PID gains will not make the feedback system stable.
The hardware must be verified before controller tuning begins.
18. Improving the Motor Controller
Our initial design provides a useful experimental platform, but several improvements would make it more capable.
Adding a home-position sensor
An incremental encoder measures relative movement.
When the ESP32 restarts, it loses its previous position reference.
A home switch could provide a repeatable mechanical reference.
The controller could perform a supervised homing sequence at low speed, establish its starting position and then permit normal operation.
Implementing cascaded control
Our current controller uses position error and measured velocity in a single feedback loop.
A more advanced design could use two nested controllers:
- An outer position controller.
- An inner velocity controller.
The position controller would determine the required velocity, while the velocity controller would regulate motor power.
Cascaded control is common in higher-performance motion-control systems.
Adding acceleration feed-forward
We could include a feed-forward control term based on the desired velocity and acceleration.
The controller would then use both a model-based estimate of the required effort and feedback corrections.
This could improve tracking if the model is sufficiently accurate.
Introducing jerk-limited movement
Our existing reference generator limits commanded acceleration.
However, the commanded acceleration can still change abruptly.
A jerk-limited S-curve profile would provide smoother transitions.
This is particularly useful for applications involving delicate mechanisms or where smooth movement is important.
Monitoring motor current
A current sensor could provide information about electrical load.
This could help identify increased friction, obstruction or unexpected mechanical loading.
Combined with encoder measurements, current monitoring would also provide a foundation for studying motor condition monitoring and fault detection.
19. Combining Parts 2 and 3
We now have two complementary systems.
The first uses a laser distance sensor to measure external movement and estimate derivatives.
The second uses a rotary encoder to measure motor movement and control its position.
Combining them creates the possibility of a motion-tracking system.
Imagine placing a moving object in front of our distance sensor.
The ESP32 estimates its position and velocity.
We then convert those measurements into a target position for the motor.
As the object moves, the motor adjusts its position to follow.
A simple implementation might use only measured target position.
A more sophisticated version could include velocity feed-forward to compensate for sensor and actuator delay.
Eventually, we could build a model-predictive control system, where the ESP32 estimates future motion and chooses a motor command accordingly.
However, any prediction would be limited by the accuracy of the sensor measurements, model assumptions and motor response.
The combined system would provide a useful experimental platform for investigating how sensing, differentiation, prediction and feedback interact.
Conclusion
In this project, we have moved beyond using differentiation simply to analyse sensor measurements.
We have introduced a system in which numerical differentiation plays a direct role in controlling physical movement.
The rotary encoder allows the ESP32 to estimate angular position.
Differentiating those measurements provides angular velocity, which can be used to damp motor movement and improve closed-loop response.
PID control then combines position error, accumulated error and velocity feedback to determine the required motor command.
By adding acceleration-limited trajectory generation, we can also investigate the difference between abrupt position commands and controlled movement profiles.
The resulting platform introduces several important engineering concepts: encoder feedback, digital control loops, numerical differentiation, signal filtering, PWM motor control, disturbance rejection and motion profiling.
It also provides a foundation for further development.
In our next article, we can combine the distance-based motion analyser from Part 2 with the motor controller developed here.
The objective will be to build a system capable of following a moving object, estimating its velocity and adjusting motor movement in response.
Coming next: Part 4 — Building a Predictive Motion-Tracking System Using Two ESP32 Projects.
Technical References
Pololu 50:1 MP 6V Micro Metal Gearmotor with Encoder
Pololu TB6612FNG Dual Motor Driver Carrier
Pololu Six-Pin Encoder Cable
Espressif Arduino-ESP32 PWM Documentation
Arduino IDE
Development note: The code and wiring in this article form a reference design. The firmware has not been compiled and run against the specified physical hardware as part of writing this article. Controller gains, electrical connections, protection measures and motion limits must be tested and validated before the mechanism is operated. Software checks are supplementary protections, not substitutes for safe mechanical design and physical motor-power isolation.