February 2024, a university robotics contest. The team bailed, the last servo burnt out and the components cupboard was empty. What was left: a four-wheel acrylic chassis, an Arduino Uno with an L293D motor shield, an HC-SR04 ultrasonic sensor on a stalk, about four coffees and one night.
I named the robot after Bhapa, the campus cat. Bhapa has her own university ID and considerably better obstacle avoidance. The resemblance was, obviously, uncanny.
The README written that night promised intelligent object following, dynamic obstacle avoidance, enhanced exploration, and proportional and adaptive speed control. The code had functions with names to match. Two years later I checked what those functions actually asked the motor shield to do.
There were two different problems. The drive adapter did not implement the left/right commands its callers thought they were sending. Even after correcting that adapter, the behaviour still treated a nearby obstacle as something to approach. Fixing the first problem could not make the second one a good policy.
Four motors do not automatically make two sides
The original sketch labels motor 1 left-front, 2 right-front, 3 left-rear and 4 right-rear. But adjustMotorSpeed(leftSpeed, rightSpeed) sends the first argument to motors 1 and 2, and the second to 3 and 4. The names say left and right; the routing says front and rear.
In the simulator’s symmetric drive approximation, each physical side therefore receives the same average: one front-wheel request and one rear-wheel request. If those requests are a and b, both side averages are (a + b) / 2.
For an ideal differential-drive model, forward speed is (v_left + v_right) / 2, while yaw rate is (v_right − v_left) / track_width. Equal side speeds give zero commanded yaw. Asking the function to turn harder does not change that equality.
The physical chassis is four-wheel skid-steer, so a perfect no-slip model is only an approximation. Unequal motors, contact forces and slipping tyres can make a real cart drift. That is different from having a controllable left/right turning command.
Reverse, represented as a very small forward
There was a second error at the library boundary. Adafruit’s AF_DCMotor::setSpeed() takes a uint8_t magnitude. Direction is a separate run() request. The original code passes signed negative numbers to setSpeed(), then calls run(FORWARD) for every motor.
Converting an integer to an unsigned eight-bit value wraps modulo 256. So −255 becomes 1, and −200 becomes 56. Neither becomes a reverse command.
Take the intended pivot request (-200, +200). In the old adapter, both front motors get magnitude 56, both rear motors get 200, and all four are told to go forward. Under the model, the physical sides each average 128. In the corrected adapter, the left pair can actually run backward while the right pair runs forward.
This is why the fix separates magnitude and direction. It constrains a signed request to ±255, sends its absolute value to setSpeed(), and chooses FORWARD, BACKWARD or RELEASE from its sign. It also groups motors 1 + 3 on the left and 2 + 4 on the right.
The type conversion is defined behaviour, not random corruption. The compiler can accept it and the motor library can do exactly what it was asked. The mistake lives in the meaning assigned to the number.
The wall was being followed successfully
The original loop has three regions. A positive distance below 25 cm selects followObject(). From 25 to just under 30 cm it selects obstacle avoidance. Everything else selects exploration.
Inside followObject(), distance is mapped from 0–25 cm to PWM 100–255. Getting closer reduces the command, but never asks for zero or reverse. A wall inside the following region is therefore not an obstacle according to this policy. It is a target being approached at a smaller, still positive speed.
That is a design error even with perfectly routed motors. The five-centimetre avoidance band does not rescue a cart that has already entered the “follow” region. A plausible function name is not an argument that its conditions match the intended behaviour.
Exploration adds a quieter state bug. It chooses random(0, 10), but the switch defines only cases 0–4. The other five choices do not necessarily mean rest: they issue no new motor command, so the previous command can remain active.
A distance is not an identity
The HC-SR04 estimates range from an acoustic round trip. With the v2 conversion, distance_cm = echo_microseconds × 0.0343 / 2. The factor of two accounts for travelling to the reflecting surface and back.
A single reading does not contain the word cat. A wall, a chair leg and Bhapa can all return a similar range. Nor is a real ultrasonic sensor an infinitely thin ray: beam width, surface angle and reflectivity affect which echo returns.
The v2 “boring” rule is a small amount of temporal memory. It remembers a reference distance and time; a change greater than 3 cm resets that reference. If the reading remains within that tolerance for more than 2.5 seconds, the robot turns away.
That is stagnation detection, not object recognition. A stationary cat can be boring by this definition. A moving robot can change its distance to a stationary wall. The rule is useful because it gives the controller an exit from a persistent situation, not because time has solved semantic classification.
Bhapa remains the more sophisticated system.
Holding a gap instead of closing it
The corrected following policy aims for 30 cm, with a ±4 cm acceptance band. Its error is distance − 30: positive means the object is farther away than the desired gap, negative means it is too close.
Outside the band, the proportional term is 9 PWM units per centimetre. The code imposes a minimum magnitude of 90 to avoid asking the geared motors for a duty at which they merely hum, and clamps the final request to 255. Inside the band it commands zero.
This is not a perfectly linear proportional controller. At 35 cm, the five-centimetre error would give 45 PWM, but the floor raises it to 90. At 34 cm, the four-centimetre band asks for zero. That discontinuity matters if noisy measurements repeatedly cross the threshold.
The too-close branch has priority below 12 cm: back away for 300 ms, then turn. Between 12 and 60 cm the controller can hold a gap or abandon a stagnant reading. Beyond that it explores, this time selecting only behaviours that exist.
The actuator adapter and the policy are now separate enough to reason about. One says how a signed side request reaches four motor ports; the other says which side requests make sense for the observed situation.
A timeout is not evidence of free space
The old call omits the third argument to pulseIn(). Arduino’s AVR C++ declaration defaults to 1,000,000 microseconds. In the exploration path the sketch measures again, so a missing echo can make two successive reads wait before that loop finishes.
During those waits, the old motor request does not automatically disappear. The random pauses, turns and loop delays add their own blind intervals. A convenient delay() is also time in which the controller is not taking a new decision.
v2 supplies a 25 ms pulse timeout. That bounds one wait, but its return policy is still a tradeoff: zero echo duration becomes the sentinel 400 cm, which the behaviour treats as far away. No echo can also mean a poor reflector, an angled surface or a sensor problem. “Unknown” and “clear” are different states.
The new sketch also retains blocking exploration, reverse and turn actions. Its final 50 ms sleep is not a guarantee of a 20 Hz sensing loop. The timeout and drive fixes improve specific faults; they do not establish a safety-rated obstacle-avoidance controller.
Three versions in a room with a model cat
The later Python study is a transcription of the firmware’s branches and waiting periods, not compiled Arduino firmware running inside a physics simulator.
Its assumptions are explicit: a 3 × 3 m room, 10 ms integration steps, a circular 9 cm robot radius, a 14 cm track width and a maximum ideal speed of 0.45 m/s. The model cat has a 12 cm radius, walks at 0.15 m/s and pauses according to its own seeded random process. The range sensor is a forward ray intersecting the room or the cat.
Three drive/behaviour combinations run with seeds 0–9 for nominally three minutes each. The middle case is labelled “v1, wiring fixed” in the archived plot, but Bot.drive() actually fixes both routing and signed drive representation. Its high-level v1 policy is unchanged. Calling it a wiring-only experiment would overstate what was isolated.

| Mean of ten simulated runs | Pinned while commanding translation | Robot-centre grid cells occupied | Time within 60 cm of the model cat |
|---|---|---|---|
| v1 with original drive faults | 86.6 % | 5.8 % | 7.1 % |
| v1 with corrected signed side drive | 69.3 % | 4.4 % | 5.3 % |
| v2 drive and policy | 0.9 % | 23.0 % | 14.0 % |
These values were reproduced from the published Python source. “Pinned” means the model attempted translation that a collision blocked; a deliberate pause is not penalized as pinning. Coverage counts which cells of a 20 × 20 grid the robot’s centre entered, not the percentage of the floor surveyed or seen by a sensor. “Near the cat” is proximity, not proof of recognizing or continuously following her.
The model has instantaneous commanded wheel response and simplified collision handling. It does not reproduce motor curves, skid, an ultrasonic beam, missing echoes or the real cost of a sonar read. Those are boundaries of the question it answers.
Within that question, the result is useful: correcting the drive adapter is necessary, but the old policy still spends most of its time pushing against something. The behaviour change matters separately.
The original adapter cannot command a left/right speed difference. Correcting the drive permits turning, but the old follow rule still approaches walls. The revised policy can hold a gap and leave a stagnant situation.
Wiring was the bug. The rule was the design mistake.
What stayed after the contest
The story is not that six hours produced an intelligent companion. It produced a real little machine, an ambitious README, and enough preserved code to ask better questions later.
The motor-port mismatch is a small version of the later sign error at a MAVLink boundary: a number only means something inside an agreed coordinate and command convention. The missing echo belongs beside the Four LEDs freshness problem: a last command is not necessarily a current instruction.
The useful habit is to separate the layers before adding sophistication. First establish that a requested reverse really reverses, and a requested turn really creates a side difference. Then inspect what the behaviour asks for near an obstacle. Only then does a nicer sensor or a more elaborate planner have a coherent system to improve.
Bhapa supplied the name. The rest needed debugging.
Follow the actual interfaces
Start with adjustMotorSpeed() and the v1 branch conditions, then compare side(), drive(), hold() and isBoring(). The distinction between a drive adapter and a behaviour is visible there without trusting a result table.
Adafruit’s motor guide explains why speed magnitude and direction are separate calls. The C++ integral-conversion rule explains the modulo wrap. For the chassis model, Modern Robotics chapter 13 develops wheeled-robot kinematics, constraints, feedback and odometry.
For the experiment, read drive(), wait() and coverage() before interpreting “room visited.” The uncropped upright photograph remains available alongside the original code and the original 2024 README.

