ESP32 stall detection: ultrasonic watchdog vs wheel encoders
An obstacle-avoiding car's worst moment is not the bump. It is the minute after, when its bumper is against a chair leg, the ultrasonic sensor hears nothing useful, and the motors keep pushing. We tested two ways an ESP32 can notice it is stuck, in 100 random simulated rooms. Wheel encoders reacted in 0.42 s (median) with no false alarms. The ultrasonic "frozen reading" watchdog from our earlier code took 1.01 s and backed out 1.6 times a minute for nothing. But encoders go blind on a slippery floor, so our firmware's default uses both.

stall_lab.py --trace from the free download.Two ways an ESP32 car can tell it is stuck
- Frozen reading (ultrasonic only). While the car drives forward, the distance should change. If it stays within 1–2 cm for 1.5 s, assume the car is pinned and back out. No extra parts; this is strategy 4 in our obstacle-avoiding code.
- Wheel encoders. Hall sensors on the motor shaft send pulses as the wheel turns, and the ESP32 counts them with an interrupt [2]. At cruise PWM the firmware knows roughly how many counts a free wheel gives in 0.3 s. Far fewer means the wheels are not turning: stalled.

The experiment
We used the 2D twin of our Kit 1 car: the same model as our 40-room avoidance test, with Kit 1's 68 mm wheels and encoders added. Every detector runs inside the same "look both ways" avoidance code; only the stuck check changes. Each one drove the same 100 random rooms (furniture at random angles, chair legs) for 120 s each, from the same starts. The HC-SR04 model has a 15° beam and a 2–400 cm range [1], 0.5 cm noise, and gets no echo from a flat surface hit at more than 40° from head-on.
- Time stuck: touching an obstacle and moving slower than 5 cm/s. Scraping along a wall does not count.
- Detect time: median time from getting stuck to the stall rule firing.
- False alarms: the stall rule fired with nothing touching the car in the last 0.5 s.
| Stall detector | Time stuck | Stuck > 3 s (events) | Longest stuck | Detect time | False alarms / min | Floor covered |
|---|---|---|---|---|---|---|
| No stall detector (only the 20 cm rule) | 7.9% | 63 | 76.9 s | - | 0.00 | 38% |
| Frozen reading 0.75 s, 1 cm | 0.5% | 3 | 10.8 s | 0.85 s | 4.12 | 40% |
| Frozen reading 1.5 s, 1 cm (our v2 code) | 1.1% | 13 | 9.4 s | 1.01 s | 1.60 | 43% |
| Frozen reading 3 s, 1 cm | 2.4% | 33 | 14.5 s | 2.40 s | 0.13 | 43% |
| Frozen reading 1.5 s, 2 cm (DETECTOR 1) | 0.7% | 5 | 4.8 s | 1.09 s | 1.60 | 43% |
| Frozen reading 1.5 s, 1 cm, echo only | 5.3% | 49 | 60.4 s | 5.74 s | 0.00 | 39% |
| Encoders 0.15 s, 35% | 0.3% | 0 | 0.7 s | 0.21 s | 0.00 | 41% |
| Encoders 0.3 s, 35% (DETECTOR 2) | 0.5% | 0 | 0.7 s | 0.42 s | 0.00 | 41% |
| Encoders 0.6 s, 35% | 0.6% | 0 | 1.0 s | 0.77 s | 0.00 | 41% |
| Encoders 0.3 s, 60% | 0.3% | 0 | 0.6 s | 0.24 s | 0.00 | 42% |
| Encoders + frozen reading (DETECTOR 3) | 0.3% | 0 | 0.7 s | 0.35 s | 1.61 | 43% |
100 rooms × 120 s per row (200 minutes of driving), tyres grip when blocked (slip 0). Detect time is the median over the stuck events the rule caught.

What we learned
- Any stall rule beats none. With only the 20 cm rule the car was stuck 7.9% of the time, with 63 events longer than 3 s; the longest lasted 77 s.
- Stuck cars are often deaf. With no detector, the sensor had no echo (reading 999) for 46% of the time the car was stuck: the bumper touches first, or the beam meets a wall at a steep angle and the sound bounces away. A rule that ignores "no echo" (echo only) has no false alarms, but every silent reading restarts its timer, so it reacted slowly (median 5.7 s) and left the car stuck 5.3% of the time.
- The frozen-reading rule's false alarms come from the same silence. 99% of them happened with no echo, for example driving across an open room. "No echo" never changes, so after 1.5 s it looks frozen. A longer timer (3 s) cuts the false alarms to 0.13 a minute but leaves the car stuck 2.4% of the time.
- 2 cm beats 1 cm. A pinned car's reading still wobbles. With a 1 cm limit the wobble sometimes restarts the timer; 2 cm cut the stuck events over 3 s from 13 to 5 and the longest from 9.4 s to 4.8 s, with the same false alarms.
- Encoders are fast and quiet. 0.3 s window, 35% line: detect time 0.42 s, no false alarms, no stuck event longer than 0.7 s. A 60% line reacted faster (0.24 s), also without false alarms in the simulation, but real motors take time to spin up, so leave margin.
- Coverage is a side effect. The frozen-reading rules covered more floor (43% vs 41%) because their false alarms act like random turns. If you want coverage, turn on purpose (see our robot vacuum experiment).
The catch: slippery floors
Encoders measure the wheels, not the car. On carpet a blocked car's tyres grip and the motors stall, so the counts drop to zero. On smooth tile the tyres can keep spinning against the obstacle, and the counts look almost normal. We don't know what your floor does, so we swept it: slip 0 means blocked wheels stop, slip 1 means they spin at full free speed.

| Slip | Encoders, 35%: time stuck | Encoders, 60% | DETECTOR 3: encoders + frozen reading |
|---|---|---|---|
| 0 | 0.5% | 0.3% | 0.3% |
| 0.25 | 0.5% | ||
| 0.5 | 7.9% | 0.4% | 0.7% |
| 0.75 | 7.9% | ||
| 1 | 7.9% | 7.9% | 0.7% |
The frozen-reading rule doesn't care about the wheels, so it is the backup. That is why the firmware's default is DETECTOR 3: on a grippy floor the encoders catch almost every stall first (time stuck 0.3%); on a slippery one the frozen reading takes over (0.7%). The price is the frozen-reading rule's false alarms (1.6 a minute). If you know your tyres grip, DETECTOR 2 has none. The README in the download shows how to check your floor in a minute: drive the car into a wall and read the counts on the Serial Monitor.

stall_lab.py --plot.Stall detection methods compared
| Method | Extra parts | Pin the sonar can't hear | Tyres spinning | False alarms | Tested here |
|---|---|---|---|---|---|
| Frozen ultrasonic reading | None | Yes (counts "no echo") | Yes | 1.6 / min | Yes |
| Frozen reading, echo only | None | No | Partly (slow) | 0 | Yes |
| Wheel encoders | Encoder motors (in Kit 1) | Yes | No | 0 | Yes |
| Encoders + frozen reading | Encoder motors | Yes | Yes | 1.6 / min | Yes |
| Motor current | A sense resistor or current sensor (the L298 has SENSE pins for a resistor to ground [4]; check whether your board brings them out) | Not tested | Not tested | Not tested | No |
The ESP32 code
The full sketch, stall_car.ino, is in the free download. Pins are Kit 1's. It uses the esp32 core 3.x ledcAttach API [3]. The two parts that matter:
1. Count pulses. One interrupt per wheel on encoder channel A, rising edge; channel B gives the direction [2].
volatile long countL = 0, countR = 0;
void IRAM_ATTR isrL() { countL += (digitalRead(ENC_L_B) ? -1 : 1) * DIR_L; }
void IRAM_ATTR isrR() { countR += (digitalRead(ENC_R_B) ? -1 : 1) * DIR_R; }
void readCounts(long &l, long &r) { noInterrupts(); l = countL; r = countR; interrupts(); }
2. Check every 0.3 s while driving straight. The encoder window only runs while cruising, so backing up and turning never count as a stall.
if (fabsf(cm - lastCm) > FROZEN_CM) { lastCm = cm; lastChange = now; } // "no echo" (999) counts too: a blind pin
const char *reason = nullptr;
if (cm < STOP_CM) reason = "near";
else if (useSonar && now - lastChange > SONAR_MS) reason = "stall: reading frozen";
else if (useEnc && cruising && now - winT >= ENC_MS) {
long l, r; readCounts(l, r);
float got = (labs(l - winL) + labs(r - winR)) / 2.0f;
float want = STALL_FRAC * CRUISE_CPS * (now - winT) / 1000.0f;
if (got < want) reason = "stall: wheels stopped";
else { winT = now; winL = l; winR = r; }
Serial.printf("%lu ms %.1f cm counts %.0f (stall below %.0f)\n", now, cm, got, want);
}
The first line is the frozen-reading rule (2 cm, and "no echo" counts as a reading). DETECTOR picks which rules run.
We compiled this exact sketch for all four DETECTOR settings on a fresh arduino-cli 1.5.2 install with the esp32 core 3.3.12 by Espressif (board ESP32 Dev Module, --warnings all): all four build.
Before trusting the numbers on your car, measure your counts per wheel turn (Kit 1's encoder_test, command p) and put them in ENC_CPR. If your motors are faster or your encoders finer, consider the ESP32's hardware pulse counter (PCNT), which counts in hardware, decodes quadrature and filters glitches [5].
Run the experiment yourself
The download also has stall_lab.py, the Python twin that runs the same logic (same constant names) in random rooms. Try your own window, threshold or floor: --enc 200 --frac 0.5 --slip 0.6. We ran it from a fresh virtual environment (Python 3.13.18, numpy 2.5.4, matplotlib 3.11.2). This is the real output:
$ python stall_lab.py --rooms 20 20 rooms x 120 s, slip 0, seed 1 detector coverage pinned pins>3s worst pin false alarms/min detects in none 38% 8.7% 14 60.4s 0.00 - frozen 1.5 s 44% 0.6% 1 4.8s 1.45 0.91 s encoders 0.3 s 43% 0.4% 0 0.6s 0.00 0.39 s both 44% 0.2% 0 0.5s 1.55 0.21 s
20 rooms is the quick default, so these numbers differ a little from the 100-room table above.
Download the stall detection code
Arduino sketch + Python twin + README. Enter your email and we'll send you a confirmation email: click it and your download starts. We'll also email you when we publish a new robot experiment (about once a week). Unsubscribe anytime.
Unzip, then follow README.md.
Limits of this simulation
- It is a 2D model with nominal Kit 1 values (0.61 m/s at full PWM, 385 counts per wheel turn); we have not yet measured them on the bench. No motor spin-up time, so real encoder windows may need to start 0.1–0.2 s after the motors do.
- Wheel slip is a single number you choose, not measured friction.
- The sensor noise (0.5 cm) and the 40° echo limit are assumptions; with a noisier sensor, raise
FROZEN_CM.
Build the car
Kit 1 is our ESP32 obstacle-avoiding car kit with encoder motors and a simulation twin of the same car. This stall detection code is part of its course.
FAQ
What is stall detection on a robot car?
Noticing that the motors are driving but the car is not moving, for example when its bumper is against a chair leg or a wall the ultrasonic sensor cannot hear. Without it, a car can stay stuck until the battery runs out.
Can an ultrasonic sensor alone detect that the car is stuck?
Mostly. Our 'frozen reading' rule backs out when the distance stays within 1 cm for 1.5 s. In 100 simulated rooms it cut the time stuck from 7.9% to 1.1%, with a median reaction of 1.01 s, but it also fired 1.6 times a minute with nothing touching the car, 99% of them while the sensor had no echo.
How do wheel encoders detect a stall?
They count how far each wheel turns. If the motors are driven at cruise speed but the wheels turned less than 35% of the expected counts in the last 0.3 s, the car is stalled. In our simulation that reacted in 0.42 s (median) with no false alarms, and the car was stuck 0.5% of the time.
When do encoders fail to detect a stall?
When the tyres keep spinning against an obstacle on a slippery floor: the wheels turn, so the counts look normal. Once blocked wheels spun at half their free speed or more, the 35% rule never fired and the car was stuck 7.9% of the time, the same as with no detector. Adding the frozen-reading rule as a backup kept it to 0.7% even with the wheels spinning at full speed.
Should I use the ESP32 pulse counter (PCNT) instead of interrupts?
For two hobby gear motors, attachInterrupt on one channel per wheel is enough and easy to read. The ESP32's PCNT peripheral counts pulses in hardware, can decode quadrature and has a glitch filter, so it is the better choice for fast motors or high-resolution encoders.
Sources
- ElecFreaks, HC-SR04 Ultrasonic Ranging Module datasheet (2 cm–4 m range, 15° measuring angle, distance in cm = echo time in µs / 58).
- Espressif, Arduino-ESP32 GPIO API (attachInterrupt(pin, handler, mode), RISING mode).
- Espressif, Arduino-ESP32 migration guide 2.x to 3.0 (new LEDC API: ledcAttach, ledcWrite by pin).
- STMicroelectronics, L298 dual full-bridge driver datasheet (SENSE A / SENSE B: "between this pin and ground is connected the sense resistor").
- Espressif, ESP-IDF Pulse Counter (PCNT) (quadrature decoding, glitch filter, 16-bit counter).
- Simulation, experiment and charts: TinyBot Forge, November 2026. Every number on this page comes from the code in the free download.
Need firmware or a simulation for your robot?
We build robot simulations and ESP32 code to order.
Email us