TINYBOT FORGE
Home › Learn › ESP32 stall detection

ESP32 stall detection: ultrasonic watchdog vs wheel encoders

Our simulation, 100 roomsArduino codeFree Python twinUpdated November 2, 2026

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.

Two plots against time. Top: the ultrasonic reading levels off after the car gets stuck. Bottom: encoder speed drops from about 650 counts per second to zero; the encoder rule is true after 0.13 s
One stuck event from our simulation, no detector running: the encoder rule (0.3 s window) is true after 0.13 s, the frozen-reading rule (2 cm, 1.5 s) after 1.44 s. One example; the medians over all 100 rooms are in the table below. Drawn by stall_lab.py --trace from the free download.

Two ways an ESP32 car can tell it is stuck

Kit 1 parts laid out, including two gear motors with Hall encoders, an L298N motor driver, an HC-SR04 ultrasonic sensor and an ESP32 board
The parts of our Kit 1 car (real photo): two JGA25-370 gear motors with Hall encoders, L298N, HC-SR04 and ESP32. The simulation uses this car's layout.

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.

Stall detectorTime stuckStuck > 3 s (events)Longest stuckDetect timeFalse alarms / minFloor covered
No stall detector (only the 20 cm rule)7.9%6376.9 s-0.0038%
Frozen reading 0.75 s, 1 cm0.5%310.8 s0.85 s4.1240%
Frozen reading 1.5 s, 1 cm (our v2 code)1.1%139.4 s1.01 s1.6043%
Frozen reading 3 s, 1 cm2.4%3314.5 s2.40 s0.1343%
Frozen reading 1.5 s, 2 cm (DETECTOR 1)0.7%54.8 s1.09 s1.6043%
Frozen reading 1.5 s, 1 cm, echo only5.3%4960.4 s5.74 s0.0039%
Encoders 0.15 s, 35%0.3%00.7 s0.21 s0.0041%
Encoders 0.3 s, 35% (DETECTOR 2)0.5%00.7 s0.42 s0.0041%
Encoders 0.6 s, 35%0.6%01.0 s0.77 s0.0041%
Encoders 0.3 s, 60%0.3%00.6 s0.24 s0.0042%
Encoders + frozen reading (DETECTOR 3)0.3%00.7 s0.35 s1.6143%

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.

Scatter plot of median detect time against false alarms per minute. Encoder settings sit at the bottom left with zero false alarms; frozen-reading settings are slower and most have false alarms
Each dot is one detector setting. A longer frozen-reading timer cuts false alarms but reacts later; encoders are faster and silent.

What we learned

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.

Line chart of time stuck against slip. Encoders alone jump to the no-detector level once slip reaches 0.5; encoders plus the frozen-reading rule stay near 1%
Encoders alone stop working once blocked wheels turn faster than the stall line. With the frozen-reading backup (DETECTOR 3) the car stays out of trouble on every floor.
SlipEncoders, 35%: time stuckEncoders, 60%DETECTOR 3: encoders + frozen reading
00.5%0.3%0.3%
0.250.5%
0.57.9%0.4%0.7%
0.757.9%
17.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.

Top view of one simulated room with the car path and circles where each stall rule fired
One room, two minutes, DETECTOR 3. Amber circles: the encoder rule fired; red: the frozen-reading rule. Drawn by stall_lab.py --plot.

Stall detection methods compared

MethodExtra partsPin the sonar can't hearTyres spinningFalse alarmsTested here
Frozen ultrasonic readingNoneYes (counts "no echo")Yes1.6 / minYes
Frozen reading, echo onlyNoneNoPartly (slow)0Yes
Wheel encodersEncoder motors (in Kit 1)YesNo0Yes
Encoders + frozen readingEncoder motorsYesYes1.6 / minYes
Motor currentA sense resistor or current sensor (the L298 has SENSE pins for a resistor to ground [4]; check whether your board brings them out)Not testedNot testedNot testedNo

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.

Free. Personal and educational use, including classes.

Limits of this simulation

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.

One email when Kit 1 opens. Unsubscribe anytime.

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

  1. ElecFreaks, HC-SR04 Ultrasonic Ranging Module datasheet (2 cm–4 m range, 15° measuring angle, distance in cm = echo time in µs / 58).
  2. Espressif, Arduino-ESP32 GPIO API (attachInterrupt(pin, handler, mode), RISING mode).
  3. Espressif, Arduino-ESP32 migration guide 2.x to 3.0 (new LEDC API: ledcAttach, ledcWrite by pin).
  4. STMicroelectronics, L298 dual full-bridge driver datasheet (SENSE A / SENSE B: "between this pin and ground is connected the sense resistor").
  5. Espressif, ESP-IDF Pulse Counter (PCNT) (quadrature decoding, glitch filter, 16-bit counter).
  6. 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