Hello friends, I hope you all are doing great. Today, I am going to share the PID Auto-Tune DC Servo Motor with ESP32 - Proteus Simulation, the eighty-fifth project of our IoT Projects series. If you have searched for PID control of a DC motor with an ESP32, how to tune a PID controller, Ziegler-Nichols tuning, relay auto-tuning, or a DC servo with an encoder and a TB6612FNG, here is a complete one in a Proteus simulation. Anyone who has tuned a PID loop by hand knows the routine: raise the gain until the motor buzzes, back off, add some derivative, try again, and still the motor overshoots or crawls to the target.
Industrial controllers have had a better way for decades: a button labelled TUNE. Press it and the controller tests the plant by itself and works out its own gains. That is what this ESP32 does with a DC servo. A bump test measures how fast the motor answers a step of voltage. A relay test makes the loop oscillate on purpose, just a little, to find the gain at which it would go unstable and the period of that oscillation. The Ziegler-Nichols rules then turn those two numbers into PID gains, and every move the servo makes is measured: rise time, overshoot and settling time. In this tutorial, we will go through the circuit, quadrature encoders, PID control, the bump test, the relay test, the tuning rules, integral windup and how a move is measured. Then we watch the whole auto-tune in the simulation and compare the quick Ziegler-Nichols gains with a no-overshoot rule. At the end, you can download the project with the sketch and every library file.
NOTICE: Our team has put a lot of effort into this project: the circuit, the code and every part in the simulation are our own work, and you get them all free. Your feedback is the fuel that keeps us going, so please tell us what you think in the comments below. And if our free projects help you, you can buy us a coffee. So, let's get started with the PID auto-tune DC servo motor with ESP32 in Proteus simulation:
What Does This Auto-Tuning DC Servo Do?
- Reads the angle: a 100-line quadrature encoder decoded x4 in an interrupt, 400 counts a turn (0.9 degrees a count).
- Measures the motor: a bump test of 4 V gives its gain K and its time constant tau.
- Finds the edge of stability: a relay test gives the ultimate gain Ku and the ultimate period Pu.
- Tunes itself: PID gains from the Ziegler-Nichols rule (quick) or a no-overshoot rule (gentle).
- Measures every move: rise time, overshoot and settling time, on an OLED, a dashboard and the serial monitor.
- Takes orders over Wi-Fi: TUNE, ZN, SOFT and GO 0 / 90 / 180 from the laptop or the phone.
It is a great project for learning closed-loop control the way it is done in practice, not just the PID formula but how to get good gains for a motor you have never seen. In the simulation, our DC servo lab models a real coreless motor with a brass flywheel, so the tests meet real inertia, friction and back-EMF.
Components Used in the Proteus Simulation
All the parts come from our Proteus libraries, each with its own tutorial. The project zip at the end includes every LIB and DLL file.
| Part | Proteus device | Library post | Connection |
|---|---|---|---|
| ESP32 DevKit V1 | ESP32 DEVKIT V1 | ESP32 DevKit V1 Library for Proteus | U1, ESP32_Servo_AutoTune.hex, Wi-Fi 192.168.1.101 |
| TB6612FNG motor driver | TB6612ADVTEP | TB6612FNG Motor Driver Library for Proteus | DRV1, PWMA D25, AIN1 D32, AIN2 D33, STBY D14 |
| DC servo lab (motor, flywheel, encoder) | DCSERVOLABTEP | DC Motor Speed and Position Control Lab Library for Proteus | U2, M+ / M- from DRV1, A / B on D26 / D27 |
| OLED SSD1306 128x64 | OLED12864WHITEADVTEP | OLED SSD1306 Library for Proteus | OLED1 on I2C, 0x3C |
| Laptop WiFi Monitor | LAPTOP WIFI MONITOR | Laptop WiFi Monitor | PC1 |
| Mobile WiFi Monitor | MOBILE WIFI MONITOR | Mobile WiFi Monitor | MOB1 |
Proteus Simulation of the DC Servo: the Circuit
| Signal | ESP32 | Goes to |
|---|---|---|
| PWMA | D25 | DRV1 PWMA: the PWM at 20 kHz, 8 bits |
| AIN1 / AIN2 | D32 / D33 | DRV1: the direction (both HIGH = brake) |
| STBY | D14 | DRV1: HIGH = the driver on |
| ENCA / ENCB | D26 / D27 | U2 A / B: the encoder, an interrupt on every edge |
| SDA / SCL | D21 / D22 | OLED1, 400 kHz |
| M1 / M2 | - | DRV1 AO1 / AO2 to U2 M+ / M- |
| +12V / +3.3V | - | DRV1 VM (the motor supply) / VCC (the logic) |
The TB6612FNG is a small dual H-bridge with MOSFET outputs; only channel A is used here. The servo lab's encoder runs on the VCC rail and its A and B outputs go straight to two GPIOs of the ESP32.
How PID Auto-Tuning Works
The DC Servo and Its Quadrature Encoder
A DC servo is just a DC motor with a position sensor and a controller that closes the loop. Here the sensor is an incremental encoder: a disc with 100 slots and two optical sensors, A and B, a quarter of a slot apart. As the disc turns, A and B give two square waves 90 degrees out of phase, and the order of their edges tells the direction: A leads B one way, B leads A the other. Counting every edge of both channels (x4 decoding) gives 4 x 100 = 400 counts a turn. The sketch keeps the last state of A and B, and on each edge looks up the pair (old state, new state) in a 16-entry table that answers +1, -1 or 0. One count is 360 / 400 = 0.9 degrees.
PID Control in Brief
The controller compares the target angle with the measured one: the error e. The proportional term pushes with a voltage Kp x e, harder the farther away it is. The integral term adds up the error over time, Ki x the sum of e dt, so a small error that friction would leave forever is slowly pushed away. The derivative term, Kd x the speed, brakes the motor as it approaches, like a shock absorber. Too much Kp and the motor overshoots and rings; too little and it crawls. Too much Ki and it overshoots even more; too little Kd and it rings. The hard part is never the formula, it is the three numbers.
Step 1: the Bump Test
First the controller learns what it is driving. It applies a step of 4 V and records the speed every 5 ms for 1.2 s. A DC motor with a flywheel answers like a first-order system: the speed rises along 1 - e^(-t / tau) towards a final speed. The final speed divided by the voltage is the gain K, in counts per second per volt, and the time it takes to reach 63.2 % of the final speed is the time constant tau. Worked example: a final speed of 4,267 counts/s at 4 V gives K = 4267 / 4 = 1,067 counts/s per volt, and 4,267 x 60 / 400 = 640 rpm.
Step 2: the Relay Test
Ziegler and Nichols' original method raised the gain of a plain P controller until the loop oscillated steadily, and noted that gain (the ultimate gain Ku) and the period (Pu). Doing that on a real machine is risky. In 1984, Astrom and Hagglund showed a safer way: replace the controller with a relay. The motor gets +d volts when the error is positive and -d volts when it is negative, with a small hysteresis eps so noise cannot make it chatter. The loop then settles by itself into a small, steady oscillation whose period is Pu, and whose amplitude a gives Ku from the describing function of a relay: Ku = 4 d / (pi x sqrt(a^2 - eps^2)). The oscillation is only as large as the relay makes it, a few degrees here, so the test is safe. Worked example: with d = 3 V, eps = 3 counts and an amplitude of 24.1 counts, Ku = 12 / (pi x sqrt(580.8 - 9)) = 12 / 75.1 = 0.160 V per count.
Step 3: the Tuning Rules
With Ku and Pu, the classic rules give the gains directly. The integral time Ti and derivative time Td give Ki = Kp / Ti and Kd = Kp x Td:
| Rule | Kp | Ti | Td | Character |
|---|---|---|---|---|
| Ziegler-Nichols PID | 0.6 Ku | Pu / 2 | Pu / 8 | quick, about a quarter-amplitude decay, some overshoot |
| No overshoot | 0.2 Ku | Pu / 2 | Pu / 3 | a third of the gain, more damping, slower but calm |
Worked example with Ku = 0.160 V per count and Pu = 185 ms: Ziegler-Nichols gives Kp = 0.096 V per count, Ki = 0.096 / 0.0925 = 1.04 V per count-second and Kd = 0.096 x 0.0231 = 0.0022 V-seconds per count. The no-overshoot rule gives Kp = 0.032, Ki = 0.35 and Kd = 0.0020. Ziegler-Nichols was designed for fast disturbance rejection in process plants, and its overshoot is well known; the no-overshoot variant trades speed for a calm arrival, which suits a servo carrying something fragile.
Integral Windup and the Derivative Kick
A servo has two classic traps. On a long move the error is large for a long time, so a plain integral grows huge while the motor is already running flat out; when the target is reached, the stored integral drives the motor far past it. That is windup. The sketch integrates only when the error is under 10 counts and the output is not saturated, and limits the integral's share to 3 V. The second trap: if the derivative acted on the error, a new target would make the error jump and the derivative would kick the motor with a spike. The sketch takes the derivative on the measured speed instead, which does not jump when the target does.
Measuring a Move
Every move is measured the way control engineers do. The rise time is the time from 10 % to 90 % of the move. The overshoot is how far past the target it goes, as a percentage of the move. The settling time is when it enters a band of 2 % of the move (at least 2 counts) and stays there. The result is reported once the motor has stayed in the band for 0.6 s.
Keeping the Loop on Time
A digital PID assumes it runs at a steady rate. This one runs every 5 ms and uses the real time since the last pass, so a web request that delays it a little does not corrupt the derivative or the integral. The OLED is the slowest thing on the board: a full frame is 1 KB over I2C, about 25 ms even at 400 kHz, which would stall five control passes. So the OLED is redrawn only while the motor rests, and once at the start of each test. The PID output is limited to 6 V, about 6,400 counts per second, which keeps the encoder's edges at least 150 microseconds apart so the interrupt never misses one.
The Arduino Code Explained
The sketch is ESP32_Servo_AutoTune.ino, built for our ESP32 DevKit V1 with the WiFi, WebServer, Wire and Adafruit SSD1306 libraries. The test settings:
const float BUMP_V = 4.0, RELAY_D = 3.0, RELAY_EPS = 3; // volts, volts, counts
The x4 decoding table and the encoder's interrupt, on every edge of both channels:
const int8_t QDEC[16] = {0, 1, -1, 0, -1, 0, 0, 1, 1, 0, 0, -1, 0, -1, 1, 0}; // (old AB, new AB) gives -1, 0, +1
const byte s = digitalRead(ENC_A) | digitalRead(ENC_B) << 1;
count += QDEC[(ab << 2) | s];
The motor: a signed voltage to the PWM and the direction pins, and a short brake after each test:
ledcWrite(PWMA, (int)(fabs(v) / VSUP * 255 + 0.5)); // (8-bit duty)
void brake() { digitalWrite(AIN1, HIGH); digitalWrite(AIN2, HIGH); ledcWrite(PWMA, 0); volts = 0; } // IN1 = IN2 = HIGH: short brake
The bump test's result: K from the final speed, tau at 63.2 %:
for (int k = 0; k < bumpN; k++) if (bumpSpeeds[k] >= 0.632 * fin) { tau = (k + 1) * DT_US / 1e6; break; }
The relay: switch when the error crosses the hysteresis; then the period from the switching times and Ku from the amplitude:
if ((relayDir > 0 && e < -RELAY_EPS) || (relayDir < 0 && e > RELAY_EPS)) { // the error crossed the hysteresis: switch
Pu = (switchAt[switches - 1] - switchAt[switches - 5]) / 2e6; // the last two full periods
Ku = 4 * RELAY_D / (PI * sqrt(max(a * a - RELAY_EPS * RELAY_EPS, 1.0f)));
The two tuning rules:
if (zn) { Kp = 0.6 * Ku; Ki = Kp / (Pu / 2); Kd = Kp * Pu / 8; strcpy(rule, "ZIEGLER-NICHOLS"); }
else { Kp = 0.2 * Ku; Ki = Kp / (Pu / 2); Kd = Kp * Pu / 3; strcpy(rule, "NO OVERSHOOT"); }
The PID with its anti-windup, the derivative on the measured speed and the 6 V limit:
if (labs(e) < 10 && fabs(u0) < VMAX) // anti-windup: integrate only near the target and
drive(constrain(Kp * e + Ki * integ - Kd * speedF, -VMAX, VMAX));
The settling band of a move:
const float band = max(0.02f * fabs(span), 2.0f);
The OLED shows the mode and the rule, the angle large with its target, K and tau, Ku and Pu, Kp and Kd, and the last move's overshoot and settling time. The dashboard's links are TUNE, ZN, SOFT and GO 0 / 90 / 180; /data gives everything as JSON.
How to Run the Proteus Simulation
- Download the project zip below and install the library files (the steps are under the download button).
- Open ESP32-Servo-AutoTune.pdsprj from the Proteus Simulation folder. Keep the HEX and the DLL files next to it.
- Press Play. At 3 s the bump test starts, then the relay test and three moves, about 14 s of simulation.
- Click U2 for the servo lab's pop-up: the flywheel, the speed, angle and voltage graphs and the last move.
- Open the Laptop WiFi Monitor (press Go): ZN or SOFT picks the rule, GO 90 moves, TUNE runs the tests again.
Simulation Results: the Auto-Tune in Proteus
We pressed Play and let the ESP32 tune the servo by itself, then made one more move from the dashboard. The times below are the simulation's clock; the whole run took 26 simulated seconds.
The Bump Test
At 3.07 s the ESP32 put 4 V on the motor. The flywheel spun up along a smooth first-order curve and settled at 4,267 counts per second, 640 rpm: K = 1,067 counts/s per volt, and 63.2 % of the final speed came after 170 ms, so tau = 170 ms. The servo lab's own fit of the same step agreed: 16.9 rad/s per volt (1,076 counts/s per volt) and a time constant of 164 ms. Then the driver braked, with both inputs HIGH, so the flywheel did not coast on for turns.
The Relay Test
At 5.42 s the relay test started around the dial's -122.4 degrees: +3 V while the error was positive, -3 V while it was negative, with 3 counts of hysteresis. After a few start-up swings the loop settled into a steady oscillation of 24.1 counts (about 22 degrees) either side, with a period of 185 ms. From those two numbers: Ku = 0.160 V per count and Pu = 185 ms. The TB6612FNG's pop-up shows the driver switching between forward and reverse, and the servo lab's graph shows the small, even oscillation of the angle.
Ziegler-Nichols: Quick, with Overshoot
The Ziegler-Nichols rule gave Kp = 0.096 V per count, Ki = 1.04 and Kd = 0.0022. The first move went from -225.9 to 90 degrees, almost a full turn: the motor reached 90 % of the way in a rise time of only 100 ms, swung 14.5 % past the target, came back and settled in 343 ms. The servo lab measured the same move independently: 14.6 % overshoot. That is the textbook Ziegler-Nichols character, fast and lively, with an overshoot many machines would not accept.
The No-Overshoot Rule: Calm Arrivals
Then the ESP32 switched to the no-overshoot rule: Kp = 0.032, Ki = 0.35, Kd = 0.0020, a third of the gain and more damping. The move to 180 degrees took a rise time of 140 ms, a little slower, with 0.0 % overshoot, and it settled in 243 ms, faster than Ziegler-Nichols because there was no swing to recover from. The long move back to -90 degrees, three quarters of a turn, gave a rise time of 140 ms, 0.7 % overshoot (a single count) and settled in 228 ms.
The motor rests 1 count (0.9 degrees) from the target after some moves: static friction holds it there and the 1-count dead band lets it rest instead of hunting back and forth, as a real servo would.
A Move from the Dashboard
The laptop's dashboard showed the tests' results, the gains and the last move. We clicked GO 90: the page came back at once with the servo still at -90.9 degrees and the target 90. The move took a rise time of 130 ms, 0.0 % overshoot and settled in 236 ms; Refresh showed the result, and the phone showed the same page.
| Move | Rule | Rise time | Overshoot | Settling |
|---|---|---|---|---|
| -225.9 to 90 deg | Ziegler-Nichols | 100 ms | 14.5 % | 343 ms |
| 90 to 180 deg | No overshoot | 140 ms | 0.0 % | 243 ms |
| 180 to -90 deg | No overshoot | 140 ms | 0.7 % | 228 ms |
| -90.9 to 90 deg (GO 90) | No overshoot | 130 ms | 0.0 % | 236 ms |
Two numbers from a safe little oscillation were enough to tune the servo: quick Ziegler-Nichols gains with their classic overshoot, or calm gains that arrive without a swing and settle even sooner.
Download the Project Files
Click the button below to download PID-Auto-Tune-DC-Servo-Motor-ESP32-Proteus-Simulation-v1.0.zip (about 3.8 MB, without the source code of the models):
PID Auto-Tune DC Servo Motor with ESP32 - Proteus Simulation V1.0- Proteus Simulation: ESP32-Servo-AutoTune.pdsprj, ESP32_Servo_AutoTune.hex and copies of the models.
- Arduino Code: ESP32_Servo_AutoTune.ino, the sketch.
- Proteus Library Files: the LIB files of every part.
- Proteus Model Files: the DLL models.
- README.txt: the installation steps, the properties, the test results and the links to every library post.
No Proteus yet? Read How to Download and Install Proteus 7 and 8. New to libraries? Follow How to Install a New Library in Proteus.
How to Install the Project Files
- Close Proteus and extract the whole zip file, for example to your Desktop.
- Copy the files from Proteus Library Files into the LIBRARY folder of Proteus.
- Copy the files from Proteus Model Files into the MODELS folder.
- Start Proteus and open the project from the Proteus Simulation folder.
Changing the Code
Open the sketch in the Arduino IDE with the TEP Boards for Proteus installed, select ESP32 Dev Module (TEP Proteus), and use Sketch > Export Compiled Binary. Put the new HEX next to the project. The bump voltage, the relay amplitude and hysteresis, the PID limit and the control period are near the top; the rules are in setRule().
Ideas to Extend the Project
- Add the classic Ziegler-Nichols "some overshoot" rule (Kp = 0.33 Ku, Td = Pu / 3) or the Tyreus-Luyben rule, and compare all of them.
- Use the bump test too: an internal-model (IMC) or lambda tuning from K and tau, with the closed-loop speed you choose.
- Add a motion profile: a trapezoidal speed ramp instead of a step target, so even the quick gains arrive smoothly.
- Change the load (the servo lab's LOAD property) and run TUNE again, to see the gains follow the plant.
- Store the gains in flash, so the servo tunes once and remembers.
- Plot the step responses on the dashboard with a small chart from the /data endpoint.
From Simulation to Real Hardware
- Check the encoder: many motors have 7 or 11 pulses a turn on the motor shaft before a gearbox; the counts a turn are pulses x 4 x the gear ratio.
- Pull-ups: open-collector encoders need pull-ups on A and B; keep the wires short or shielded.
- Start gently: try the relay test with a smaller d first, and keep a hand near the power switch.
- Friction and backlash: a geared motor has a dead zone; the integral and the 1-count dead band handle a little of it.
- Supply: the TB6612FNG takes up to 15 V and 1.2 A continuous per channel; a bigger motor needs a bigger driver.
Troubleshooting
- The motor does not turn: STBY (D14) must be HIGH, VM on +12 V, AO1 and AO2 to M+ and M-.
- The angle runs away during the relay test: A and B (or M+ and M-) are swapped and the feedback is positive; swap one pair.
- The relay test gives a huge amplitude: lower RELAY_D; a loose or slipping encoder also looks like this.
- The moves ring: use SOFT, or lower Kp; a heavy load lowers Ku, so run TUNE again.
- The OLED stays dark: SDA and SCL on D21 and D22, VCC on 3.3 V; it is redrawn only while the motor rests.
Limitations of the Simulation
- The servo is our library's model: a coreless motor with a flywheel, viscous and dry friction and back-EMF, not every detail of a real gearbox or encoder.
- The rules are classic starting points, not an optimum; a real machine is often fine-tuned after the auto-tune.
- The network to the laptop and the phone is simulated inside Proteus.
- ESP32 is a product of Espressif Systems and the TB6612FNG of Toshiba; this project is not made or endorsed by them or by Labcenter.
So, that was all about the PID Auto-Tune DC Servo Motor with ESP32 - Proteus Simulation. I hope it helps you understand how a controller can measure its own plant, why a relay test finds the edge of stability so safely, how the Ziegler-Nichols rules turn two numbers into a PID, and why the integral must wait near the target, all tested in a simulation before you tune a real motor. More projects with the ESP32 and the Raspberry Pi 5 are coming. If you have any questions, ask in the comments and I will help you out. Till the next tutorial, take care and have fun!