This is my 2WD rover: a small two-wheel-drive robot, driven by an Arduino, that roams around the house on its own and avoids obstacles with an ultrasonic sonar mounted on a servo. I built it in 2012 as a beginner, and watching it wander from room to room was very satisfying (and quite surprising, too). I still have to give it a name.

Update November 2026: I rewrote this article from scratch with current parts, a new wiring diagram, a completely new sketch and a step-by-step guide. The 2012 code had been partly lost when the blog was migrated, and the old circuit had several limits (no reverse, 9 V batteries, servo powered by the Arduino): they are all fixed now.

The first prototype in action. More of my videos and projects are on my YouTube channel.

What you need

Tools: small screwdriver, multimeter, soldering iron (only for the capacitors on the motors, if the wires are not already soldered).

How it works

The idea is simple: the rover drives forward until the sonar sees an obstacle that is too close. Then it stops, turns its “head” right and left, measures the free space in five directions and decides where to go. If it is boxed in, it backs up and spins by a random angle.

The first prototype always made the most obvious choice, and that made it predictable: in a hallway it went back and forth, in a corner it always turned the same way. The 2026 version adds a carefully measured dose of randomness: a gently wandering path, choices weighted by free space, a memory that avoids repeating the same turn, spontaneous turns, and pauses to look around. The result looks almost like a curious little animal, and it covers the room much better.

The sketch is organized as a state machine: at any moment the rover is in one state (CRUISE, SCAN, TURN, REVERSE or LOW BATTERY) and moves to another when something happens. The loop never blocks for long, except during a scan, which takes just over a second.

State machine of the obstacle-avoiding rover sketch: cruise, scan, turn, reverse and low battery states

The sketch states and what triggers each transition.

Parts

Part What it does Notes Where to buy
Arduino UNO R4 Minima (or UNO R3, UNO R4 WiFi) The brain The R4 accepts 6 to 24 V on VIN, ideal with two 18650 cells. The R3 wants at least 7 V on VIN: it works, but it may reset when the batteries are almost flat Amazon
2WD chassis with 2 TT 1:48 gear motors, wheels and caster The mechanics TT motors are rated 3–6 V: the sketch limits the average voltage with PWM. You don’t need the 4×AA holder that comes with the kit Amazon · AliExpress
TB6612FNG driver Drives the two motors: speed, forward, reverse, brake 1.2 A continuous per channel, much more efficient than the old L298N Amazon · AliExpress
HC-SR04 sonar Measures distance (2–400 cm) 5 V supply. Struggles with fabric and steeply angled surfaces Amazon · AliExpress
MG90S 9 g micro servo (or SG90) Turns the sonar to look right and left The metal gears of the MG90S last longer Amazon · AliExpress
2 Li-ion 18650 cells + holder with switch Power: 7.4 V nominal (6.6–8.4 V) Buy brand-name cells (Samsung, LG, Molicel, Sony/Murata) from a reliable seller: there are many fakes with inflated capacity Holder: Amazon · AliExpress
Li-ion charger Charges the 18650 cells outside the rover A “smart” one that charges to 4.2 V and stops by itself Amazon
Mini560 5 V step-down A separate, robust supply for the servo Sold with fixed outputs (3.3 / 5 / 9 / 12 V): get the 5 V one and measure it before connecting Amazon · AliExpress
3 × 10 kΩ resistors Divider to read the battery voltage Two in series make the 20 kΩ in the diagram Amazon · AliExpress
2 × 100 nF ceramic capacitors Reduce the electrical noise from the motors One soldered directly across the terminals of each motor Amazon · AliExpress
2 × 470 µF electrolytic capacitors (16 V or more) Energy reservoirs next to the driver and the servo Mind the polarity: the stripe on the body marks the negative lead Amazon · AliExpress
Breadboard and jumper wires Solderless connections A 170-point mini breadboard fits nicely on the chassis Amazon · AliExpress

If you would rather start from a complete kit, with instructions and ready-made examples, the ELEGOO Smart Robot Car V4 has almost everything (it has four wheels, a UNO R3-compatible board and its own motor shield). You can adapt the sketch in this article by changing the pins in its first section.

Lithium battery safety

18650 cells store a lot of energy. Never short the two terminals: a screwdriver or a wire touching + and − can heat everything up in seconds. Charge them only with a Li-ion charger, don’t leave them charging unattended, and recycle them (in a battery collection bin) if they are dented or swollen. The sketch stops the rover when the voltage drops below 3.3 V per cell, because discharging them further damages them.

Wiring diagram

Wiring diagram of the Arduino 2WD rover: 2x18650 battery, TB6612FNG motor driver, HC-SR04 sonar on a 9 g servo, 5 V step-down and battery voltage divider

The complete diagram: click to enlarge. Wire colors follow the legend at the bottom.

The diagram has four blocks:

  • Power: the two 18650 cells in series, through the switch, form the VBAT line (red). Three branches start from it: the driver’s VM (the motors), the Arduino’s VIN and the step-down input.
  • Motors: the TB6612FNG gets a PWM speed signal and two direction signals for each motor from the Arduino. The STBY pin must be high, otherwise the driver stays off.
  • Head: the servo takes its 5 V from the step-down, not from the Arduino. This is the most important fix compared with the old circuit: a servo that starts abruptly can draw half an amp and reset the Arduino. The sonar draws very little and can stay on the Arduino’s 5 V.
  • Battery monitor: the 20 kΩ / 10 kΩ divider splits VBAT by three, so the 8.4 V of a full battery becomes 2.8 V, which the A2 input reads without trouble.

All grounds (GND) must be connected together: battery, driver, Arduino, step-down, servo and sonar. It is the most common mistake: without a common ground the signals have no reference and the rover behaves strangely.

From To Function
Battery + (after the switch) TB6612 VM · Arduino VIN · Mini560 IN+ · 20 kΩ resistor 7.4 V power
Battery − Common GND Ground
Arduino 5V TB6612 VCC · HC-SR04 VCC Driver logic and sonar
Arduino D5 / D7 / D8 TB6612 PWMA / AIN1 / AIN2 Left motor: speed and direction
Arduino D6 / D4 / D2 TB6612 PWMB / BIN1 / BIN2 Right motor: speed and direction
Arduino A1 TB6612 STBY Enables the driver
TB6612 AO1 / AO2 Left motor Motor A output
TB6612 BO1 / BO2 Right motor Motor B output
Arduino D9 Servo SIG (orange or yellow wire) Head position
Mini560 OUT+ Servo V+ (red wire) 5 V for the servo
Arduino D10 / D11 HC-SR04 Trig / Echo Distance measurement
Divider midpoint Arduino A2 Battery voltage ÷ 3
Arduino A3 nothing Left unconnected: its “noise” seeds the random numbers

Why are the motors on pins 5 and 6 and not on the usual 9 and 10? On the UNO R3 the Servo library uses Timer1, which disables PWM exactly on pins 9 and 10. With the motors on pins 5 and 6 the sketch works the same on the R3 and the R4.

Step-by-step assembly

1. Prepare the motors

If the gear motors don’t already have wires, solder two leads (red and black, about 15 cm / 6 in) to each one. Then solder a 100 nF ceramic capacitor directly across the two terminals of each motor: it has no polarity. Brushed motors produce tiny sparks, and this capacitor absorbs most of the noise before it reaches the wires. Slide the encoder discs onto the shafts if your kit includes them: you don’t need them yet, but they will come in handy (see the ideas for future upgrades).

2. Build the chassis

Fix the two motors with the brackets and the long screws from the kit, wires facing inward. Mount the rear caster with its spacers and push the wheels on. The wheels must turn without rubbing on the chassis: if they touch, push them a little less far onto the shaft.

3. Battery and switch

Fix the 2×18650 holder on the lower deck with thick double-sided tape or cable ties, as central as possible and close to the wheel axle: the batteries are almost half the weight of the rover and decide how stable it is in turns. Keep the switch within reach. Don’t insert the cells yet.

4. Prepare the 5 V step-down

Before mounting it, connect the Mini560 to the battery (IN+ to the positive after the switch, GND to the negative), switch on and measure the output with the multimeter: you should read about 5.0 V. If you read a different value you have the wrong version: don’t connect the servo. Then switch off and fix the module near where the servo will go, with the 470 µF capacitor across its output (long leg, or the side without the stripe, on +).

5. Arduino and driver

Fix the Arduino on the upper deck with standoffs or M3 screws, with the USB port facing the back so you can reach it. Plug the TB6612FNG into the mini breadboard, straddling the center groove, and stick the breadboard next to the Arduino. Add the second 470 µF capacitor between VM and GND of the driver, as close to its pins as possible.

6. Wire the motors

Connect the left motor to AO1/AO2 and the right one to BO1/BO2. Don’t worry about polarity: if a wheel spins the wrong way you fix it in the sketch (step 11), without touching the wires. Then connect the control signals following the table: D5, D7, D8 for motor A; D6, D4, D2 for motor B; A1 to STBY; the Arduino’s 5V and GND to the driver’s VCC and GND.

7. Mount the head: servo and sonar

Fix the servo at the front of the chassis with the shaft pointing up. Before screwing on the horn, move the servo to its center: connect the servo, the Arduino and the step-down, upload this tiny sketch and leave it running.

#include <Servo.h>
Servo head;
void setup() {
  head.attach(9);
  head.write(90);   // center
}
void loop() {}

With the servo held at 90°, fit the horn and the sonar bracket so the HC-SR04 looks straight ahead. If you can’t align it perfectly, no problem: you will correct it by a few degrees with SERVO_CENTER. Connect the sonar: VCC to the Arduino’s 5V, Trig to D10, Echo to D11, GND to ground. Use wires long and soft enough to let the head turn ±70° without pulling.

8. Battery divider

On the breadboard, put two 10 kΩ resistors in series (making 20 kΩ) between VBAT and a midpoint, and a third 10 kΩ between the midpoint and GND. Connect the midpoint to A2. If you decide not to fit the divider, set USE_VBAT = false in the sketch, but then it is up to you not to over-discharge the batteries.

9. Check before powering up

With no cells inserted and the multimeter in continuity mode, check that VBAT and GND are not shorted and that all grounds beep together. Double-check the orientation of the two electrolytic capacitors and of the servo connector (the brown or black wire is ground). Two minutes here can save a burned part.

10. Upload the sketch

Install the Arduino IDE 2. For the UNO R4 open Tools › Board › Boards Manager, search for “UNO R4” and install the Arduino UNO R4 Boards package; for the R3 the AVR package is already included. The Servo library is built into the IDE: no other libraries are needed. Download the sketch (rover_2wd.zip) or copy it from the next section, connect the Arduino via USB and upload it. For the first tests keep the rover lifted, resting on a box with the wheels in the air: you can watch what it does without chasing it around the room.

11. Calibration

Open the Serial Monitor at 115200 baud: the rover prints what it is doing (CRUISE, SCAN with the measured distances, TURN, REVERSE). Then, in this order:

  1. Wheel direction: in CRUISE both wheels must push forward. If one spins backwards, set its LEFT_DIR or RIGHT_DIR to -1.
  2. Head side: during SCAN the first value printed is “-70 deg”, and the sonar must look left. If it looks right, set SERVO_DIR = -1.
  3. Left and right motors: put the rover on the floor and hold a hand in front of it, 20 cm (8 in) away, slightly to the right. It must turn left, toward the free space. If it does the opposite, motors A and B are swapped: swap their wires on the driver.
  4. Driving straight: set wanderGain to 0 in a test personality and see if the rover pulls to one side. Add a few units to LEFT_TRIM or RIGHT_TRIM for the slower motor.
  5. Degrees of rotation: measure how many milliseconds the rover takes to spin a full circle at turnPwm and divide by 360: that is MS_PER_DEG. It depends on motors, wheels, floor and battery charge, so an estimate is fine.

The code

The sketch is just over 400 lines long, but it is split into well-separated sections: pins, parameters, helper functions (random numbers, motors, sonar), decisions and states. All the numbers worth changing are in the TUNING section. Download rover_2wd.zip.

/*
  2WD obstacle-avoiding rover - ccworld.it (2026 edition)
  ------------------------------------------------------
  Board : Arduino UNO R4 Minima / UNO R4 WiFi (also works on UNO R3)
  Driver: TB6612FNG dual H-bridge
  Sensor: HC-SR04 ultrasonic sonar mounted on a 9 g servo
  Power : 2 x 18650 Li-ion (7.4 V nominal) through an on/off switch

  Behaviour, in short:
  - CRUISE  : drives forward along a gently wandering path, slows down
              near obstacles, and every now and then turns on its own
              (Levy-flight style runs) or stops to look around.
  - SCAN    : when something is closer than stopCm, it looks at five
              angles and picks a direction with a weighted random choice
              (more free space = more likely), avoiding repeating the
              same side too often.
  - REVERSE : if every direction is blocked, or the rover looks stuck,
              it backs up and spins by a random angle.

  All the numbers you may want to change are in the TUNING section.
  License: MIT - use it, change it, share it.
*/

#include <Arduino.h>
#include <Servo.h>
#include <math.h>

// ======================= PINS =======================
// PWM pins 5 and 6 are used for the motors because the Servo library
// on the UNO R3 takes over Timer1 and disables PWM on pins 9 and 10.
const uint8_t PIN_PWMA  = 5;   // left motor speed (PWM)
const uint8_t PIN_AIN1  = 7;   // left motor direction
const uint8_t PIN_AIN2  = 8;
const uint8_t PIN_PWMB  = 6;   // right motor speed (PWM)
const uint8_t PIN_BIN1  = 4;   // right motor direction
const uint8_t PIN_BIN2  = 2;
const uint8_t PIN_STBY  = A1;  // TB6612 standby: HIGH = driver enabled
const uint8_t PIN_SERVO = 9;   // servo signal (orange/yellow wire)
const uint8_t PIN_TRIG  = 10;  // HC-SR04 Trig
const uint8_t PIN_ECHO  = 11;  // HC-SR04 Echo
const uint8_t PIN_VBAT  = A2;  // battery voltage through a 20k/10k divider
const uint8_t PIN_NOISE = A3;  // leave UNCONNECTED: used to seed random()

// ======================= TUNING =======================
// A "personality" groups the parameters that shape the movement.
struct Personality {
  uint8_t  cruisePwm;    // forward speed (0-255, capped by MAX_PWM)
  uint8_t  turnPwm;      // speed while spinning in place
  uint8_t  stopCm;       // obstacle closer than this -> stop and scan
  uint8_t  slowCm;       // start slowing down below this distance
  float    wanderGain;   // 0 = straight lines, 1 = very wobbly path
  float    epsilon;      // chance of a purely exploratory choice (0-1)
  uint16_t levyMinMs;    // shortest straight run before a spontaneous turn
  float    levyAlpha;    // Pareto exponent: lower = rarer, longer runs
  uint32_t curiosityMs;  // average time between look-around pauses (0 = off)
};

//                           cruise turn stop slow wander eps   levyMin alpha curiosity
const Personality CALM    = {140,   150,  25,  60,  0.15f, 0.05f, 4000, 1.8f, 0};
const Personality CURIOUS = {155,   160,  25,  60,  0.35f, 0.20f, 2000, 1.5f, 30000};
const Personality NERVOUS = {175,   175,  30,  70,  0.60f, 0.35f,  800, 1.2f, 12000};

Personality P = CURIOUS;               // <- pick the personality here

const uint8_t  MAX_PWM      = 180;     // TT motors are rated 3-6 V: 180/255 of 8.4 V is about 6 V
const int      SERVO_CENTER = 90;      // change it if the sonar does not look straight ahead
const int8_t   SERVO_DIR    = 1;       // set to -1 if the sonar looks LEFT when it should look RIGHT
const int8_t   LEFT_DIR     = 1;       // set to -1 if the left wheel spins backwards
const int8_t   RIGHT_DIR    = 1;       // set to -1 if the right wheel spins backwards
const int8_t   LEFT_TRIM    = 0;       // add a few units to the slower motor to drive straight
const int8_t   RIGHT_TRIM   = 0;
const float    MS_PER_DEG   = 5.5f;    // calibrate: milliseconds to spin 1 degree at turnPwm
const uint8_t  MIN_FREE_CM  = 35;      // a direction counts as "free" above this
const uint16_t MAX_CM       = 300;     // readings above this (or no echo) are treated as "far"
const uint8_t  HEAD_WOBBLE  = 12;      // degrees the sonar sweeps while cruising (0 = off)
const bool     USE_VBAT     = true;    // false if you did not fit the voltage divider
const float    VBAT_RATIO   = 3.0f;    // (20k + 10k) / 10k
const float    VBAT_MIN     = 6.6f;    // 2 x 3.3 V: below this the rover stops to protect the cells
const float    ADC_REF      = 5.0f;    // UNO R3 / R4 Minima / R4 WiFi analog reference
const bool     DEBUG        = true;    // print what the rover is thinking on the Serial Monitor

const int8_t  SCAN_ANGLES[] = {-70, -35, 0, 35, 70};   // negative = left, positive = right
const uint8_t N_SCAN = sizeof(SCAN_ANGLES) / sizeof(SCAN_ANGLES[0]);

// ======================= STATE =======================
enum State { CRUISE, SCAN, TURN, REVERSE, LOW_BATTERY };
State state = CRUISE;

Servo head;
unsigned long stateStart = 0;       // when the current state began
unsigned long stateLength = 0;      // how long TURN / REVERSE last
int  turnSign = 1;                  // +1 = spin right, -1 = spin left
bool greedyScan = false;            // true = pick the most open direction (curiosity pause)

float wander = 0;                   // smoothed random value in [-1, 1]
uint16_t lastCm = MAX_CM;           // last forward distance
unsigned long lastPing = 0, lastWander = 0, lastVbatCheck = 0;
unsigned long nextLevyAt = 0, nextCuriosityAt = 0;
uint16_t progressRefCm = MAX_CM;    // stuck detection
unsigned long progressAt = 0;
int8_t lastSide = 0;                // side chosen at the previous scan (-1/0/+1)
uint8_t sameSideCount = 0;          // how many times in a row
uint8_t lowVbatCount = 0;

// ======================= RANDOM HELPERS =======================
float frand() {                                  // uniform in [0, 1)
  return random(0, 10000) / 10000.0f;
}

float gaussian() {                               // standard normal (Box-Muller)
  float u1 = 1.0f - frand();                     // (0, 1]
  float u2 = frand();
  return sqrtf(-2.0f * logf(u1)) * cosf(2.0f * PI * u2);
}

unsigned long paretoMs(uint16_t xm, float alpha, unsigned long cap) {
  // Heavy-tailed run length: mostly short runs, sometimes very long ones.
  float u = 1.0f - frand();                      // (0, 1]
  float x = xm / powf(u, 1.0f / alpha);
  return (x > cap) ? cap : (unsigned long)x;
}

unsigned long exponentialMs(uint32_t mean) {     // waiting time of a Poisson process
  return (unsigned long)(-logf(1.0f - frand()) * mean);
}

void seedRandom() {
  // Collect the least significant bit of a floating analog pin.
  uint32_t s = 0;
  for (uint8_t i = 0; i < 32; i++) {
    s = (s << 1) | (analogRead(PIN_NOISE) & 1);
    delayMicroseconds(300);
  }
  randomSeed(s ^ micros());
}

// ======================= MOTORS =======================
void setMotor(uint8_t pwmPin, uint8_t in1, uint8_t in2, int speed) {
  speed = constrain(speed, -(int)MAX_PWM, (int)MAX_PWM);
  if (speed > 0)      { digitalWrite(in1, HIGH); digitalWrite(in2, LOW);  }
  else if (speed < 0) { digitalWrite(in1, LOW);  digitalWrite(in2, HIGH); }
  else                { digitalWrite(in1, HIGH); digitalWrite(in2, HIGH); } // short brake
  analogWrite(pwmPin, abs(speed));
}

void drive(int left, int right) {
  if (left != 0)  left  += (left > 0 ? LEFT_TRIM : -LEFT_TRIM);
  if (right != 0) right += (right > 0 ? RIGHT_TRIM : -RIGHT_TRIM);
  setMotor(PIN_PWMA, PIN_AIN1, PIN_AIN2, left * LEFT_DIR);
  setMotor(PIN_PWMB, PIN_BIN1, PIN_BIN2, right * RIGHT_DIR);
}

void stopMotors() { drive(0, 0); }

// ======================= SONAR AND HEAD =======================
void look(int angle) {                           // angle in degrees, negative = left
  head.write(constrain(SERVO_CENTER + SERVO_DIR * angle, 0, 180));
}

uint16_t pingOnce() {
  digitalWrite(PIN_TRIG, LOW);
  delayMicroseconds(2);
  digitalWrite(PIN_TRIG, HIGH);
  delayMicroseconds(10);
  digitalWrite(PIN_TRIG, LOW);
  unsigned long us = pulseIn(PIN_ECHO, HIGH, 25000UL);   // about 4 m max
  if (us == 0) return MAX_CM;                            // no echo = nothing in range
  unsigned long cm = us / 58;
  return (cm > MAX_CM) ? MAX_CM : (uint16_t)cm;
}

uint16_t pingMedian() {                          // median of 3 removes single bad echoes
  uint16_t a = pingOnce(); delay(30);
  uint16_t b = pingOnce(); delay(30);
  uint16_t c = pingOnce();
  if (a > b) { uint16_t t = a; a = b; b = t; }
  if (b > c) { uint16_t t = b; b = c; c = t; }
  if (a > b) { uint16_t t = a; a = b; b = t; }
  return b;
}

void scanAll(uint16_t d[]) {
  for (uint8_t i = 0; i < N_SCAN; i++) {
    look(SCAN_ANGLES[i]);
    delay(i == 0 ? 350 : 180);                   // let the servo arrive and settle
    d[i] = pingMedian();
    if (DEBUG) {
      Serial.print(F("  ")); Serial.print(SCAN_ANGLES[i]);
      Serial.print(F(" deg: ")); Serial.print(d[i]); Serial.println(F(" cm"));
    }
  }
  look(0);
}

// ======================= DECISIONS =======================
// Returns the index of the chosen angle, or -1 if everything is blocked.
int chooseDirection(const uint16_t d[], bool greedy) {
  float w[N_SCAN];
  float total = 0;
  uint8_t freeCount = 0;
  for (uint8_t i = 0; i < N_SCAN; i++) {
    w[i] = 0;
    if (d[i] < MIN_FREE_CM) continue;
    float room = d[i] - MIN_FREE_CM + 1;
    w[i] = room * room;                          // more room = much more likely
    int8_t side = (SCAN_ANGLES[i] > 0) - (SCAN_ANGLES[i] < 0);
    if (side != 0 && side == lastSide) {         // anti-loop memory
      w[i] *= powf(0.6f, sameSideCount);
    }
    total += w[i];
    freeCount++;
  }
  if (freeCount == 0) return -1;

  if (greedy) {                                  // curiosity: go where there is most room
    int best = 0;
    for (uint8_t i = 1; i < N_SCAN; i++) if (d[i] > d[best]) best = i;
    return best;
  }

  if (frand() < P.epsilon) {                     // exploration: any free direction
    uint8_t k = random(freeCount);
    for (uint8_t i = 0; i < N_SCAN; i++) {
      if (w[i] > 0) { if (k == 0) return i; k--; }
    }
  }

  float r = frand() * total;                     // roulette-wheel selection
  for (uint8_t i = 0; i < N_SCAN; i++) {
    if (w[i] <= 0) continue;
    if (r < w[i]) return i;
    r -= w[i];
  }
  return N_SCAN / 2;                             // not reached, kept for safety
}

void rememberSide(int angle) {
  int8_t side = (angle > 0) - (angle < 0);
  if (side != 0 && side == lastSide) sameSideCount++;
  else sameSideCount = 0;
  lastSide = side;
}

// ======================= STATE CHANGES =======================
void startCruise();                              // defined below

void enter(State s) {
  state = s;
  stateStart = millis();
}

void startTurn(int angle) {
  if (angle == 0) { startCruise(); return; }
  turnSign = (angle > 0) ? 1 : -1;
  float jitter = 0.8f + 0.4f * frand();          // +/-20 %: never quite the same turn
  stateLength = (unsigned long)(abs(angle) * MS_PER_DEG * jitter);
  if (DEBUG) { Serial.print(F("TURN ")); Serial.println(angle); }
  enter(TURN);
}

void startReverse() {
  stateLength = 400 + random(500);
  if (DEBUG) Serial.println(F("REVERSE"));
  enter(REVERSE);
}

void startScan(bool greedy) {
  stopMotors();
  greedyScan = greedy;
  if (DEBUG) Serial.println(greedy ? F("LOOK AROUND") : F("SCAN"));
  enter(SCAN);
}

void startCruise() {
  look(0);
  progressRefCm = lastCm;
  progressAt = millis();
  nextLevyAt = millis() + paretoMs(P.levyMinMs, P.levyAlpha, 60000UL);
  if (DEBUG) Serial.println(F("CRUISE"));
  enter(CRUISE);
}

// ======================= STATES =======================
void doCruise(unsigned long now) {
  // 1. Head wobble: a slow sweep widens what the sonar can see.
  int offset = 0;
  if (HEAD_WOBBLE > 0) {
    offset = (int)(HEAD_WOBBLE * sinf(now * 2.0f * PI / 1200.0f));
    look(offset);
  }

  // 2. Distance, at most every 60 ms (shorter intervals catch old echoes).
  if (now - lastPing >= 60) {
    lastPing = now;
    lastCm = pingOnce();
    if (lastCm < P.stopCm) { startScan(false); return; }

    // Stuck detection, only with the sonar roughly straight ahead.
    if (abs(offset) <= 4) {
      if (abs((int)lastCm - (int)progressRefCm) > 4 || lastCm >= MAX_CM - 20) {
        progressRefCm = lastCm;
        progressAt = now;
      } else if (now - progressAt > 2500) {
        if (DEBUG) Serial.println(F("STUCK?"));
        startReverse();
        return;
      }
    }
  }

  // 3. Wander: a random value that drifts smoothly (Ornstein-Uhlenbeck).
  if (now - lastWander >= 100) {
    lastWander = now;
    wander += -0.15f * wander + P.wanderGain * 0.25f * gaussian();
    wander = constrain(wander, -1.0f, 1.0f);
  }

  // 4. Speed: slow down progressively as the obstacle gets closer.
  float k = 1.0f;
  if (lastCm < P.slowCm) {
    k = 0.45f + 0.55f * (float)(lastCm - P.stopCm) / (P.slowCm - P.stopCm);
    k = constrain(k, 0.45f, 1.0f);
  }
  float base = P.cruisePwm * k;
  drive((int)(base * (1.0f + 0.35f * wander)), (int)(base * (1.0f - 0.35f * wander)));

  // 5. Spontaneous behaviour.
  if (now >= nextLevyAt) {                       // end of a Levy run: turn on its own
    int angle = (int)(60 + 40 * gaussian());
    angle = constrain(angle, 20, 160);
    startTurn(random(2) ? angle : -angle);
    return;
  }
  if (P.curiosityMs > 0 && now >= nextCuriosityAt) {
    nextCuriosityAt = now + exponentialMs(P.curiosityMs);
    startScan(true);
  }
}

void doScan() {
  uint16_t d[N_SCAN];
  scanAll(d);
  int i = chooseDirection(d, greedyScan);
  if (i < 0) {                                   // boxed in
    startReverse();
    return;
  }
  int angle = SCAN_ANGLES[i];
  if (angle == 0 && !greedyScan) {               // centre free again: small random nudge
    angle = random(2) ? 15 : -15;
  }
  rememberSide(angle);
  startTurn(angle);
}

void doTurn(unsigned long now) {
  drive(P.turnPwm * turnSign, -P.turnPwm * turnSign);
  if (now - stateStart >= stateLength) {
    stopMotors();
    delay(80);
    startCruise();
  }
}

void doReverse(unsigned long now) {
  drive(-P.cruisePwm, -P.cruisePwm);
  if (now - stateStart >= stateLength) {
    stopMotors();
    delay(80);
    int angle = 110 + random(90);                // escape: 110-199 degrees, random side
    startTurn(random(2) ? angle : -angle);
  }
}

// ======================= BATTERY =======================
float readVbat() {
  long sum = 0;
  for (uint8_t i = 0; i < 8; i++) sum += analogRead(PIN_VBAT);
  return (sum / 8.0f) * ADC_REF / 1023.0f * VBAT_RATIO;
}

void checkBattery(unsigned long now) {
  if (!USE_VBAT || now - lastVbatCheck < 2000) return;
  lastVbatCheck = now;
  float v = readVbat();
  if (v < 3.0f) return;                          // USB only (switch off): nothing to protect
  if (v < VBAT_MIN) lowVbatCount++; else lowVbatCount = 0;
  if (lowVbatCount >= 3 && state != LOW_BATTERY) {
    stopMotors();
    digitalWrite(PIN_STBY, LOW);                 // driver off
    head.detach();
    if (DEBUG) { Serial.print(F("LOW BATTERY ")); Serial.println(v); }
    enter(LOW_BATTERY);
  }
}

// ======================= SETUP / LOOP =======================
void setup() {
  pinMode(PIN_PWMA, OUTPUT); pinMode(PIN_AIN1, OUTPUT); pinMode(PIN_AIN2, OUTPUT);
  pinMode(PIN_PWMB, OUTPUT); pinMode(PIN_BIN1, OUTPUT); pinMode(PIN_BIN2, OUTPUT);
  pinMode(PIN_STBY, OUTPUT);
  pinMode(PIN_TRIG, OUTPUT); pinMode(PIN_ECHO, INPUT);
  pinMode(LED_BUILTIN, OUTPUT);
  stopMotors();
  digitalWrite(PIN_STBY, HIGH);

  if (DEBUG) Serial.begin(115200);
  seedRandom();
  head.attach(PIN_SERVO);
  look(0);
  delay(2000);                                   // time to put the rover on the floor
  nextCuriosityAt = millis() + (P.curiosityMs ? exponentialMs(P.curiosityMs) : 0);
  startCruise();
}

void loop() {
  unsigned long now = millis();
  checkBattery(now);
  switch (state) {
    case CRUISE:      doCruise(now);  break;
    case SCAN:        doScan();       break;
    case TURN:        doTurn(now);    break;
    case REVERSE:     doReverse(now); break;
    case LOW_BATTERY:                            // slow blink, nothing else
      digitalWrite(LED_BUILTIN, (now / 1000) % 2);
      break;
  }
}

A few choices worth explaining:

  • No long delay() calls. Each state checks with millis() whether it is time to do something. This way the rover measures, wanders and checks the battery at the same time.
  • The sonar is read without libraries. pulseIn() with a 25 ms timeout measures the echo length; dividing by 58 gives centimeters. If no echo comes back, the distance counts as “far” (300 cm). During a scan the sketch takes the median of three readings, which discards bad echoes.
  • Active braking. At zero speed the driver shorts the motors (IN1 and IN2 high): the rover stops at once instead of coasting.
  • Limited top speed. A full battery gives 8.4 V, too much for 6 V motors: MAX_PWM = 180 keeps them at about 6 V on average.

Algorithms for less predictable movement

A robot that always reacts the same way to the same situation easily falls into a loop: it goes back and forth in a hallway, circles the same table, always gets stuck in the same corner. You don’t need artificial intelligence to break out of it: it is enough to add randomness in the right places, without giving up on logic. Here are the techniques used in the sketch, from the simplest to the subtlest.

1. Weighted roulette choice

After a scan the rover does not always pick the most open direction. It draws one at random, giving each direction a weight proportional to the square of the free space beyond the threshold: weight = (distance − 35)². Directions under 35 cm get zero weight and are never chosen. Squaring makes very open directions strongly favored, but not certain.

Direction −70° −35° 0° +35° +70°
Measured distance 120 cm 80 cm 20 cm 45 cm 200 cm
Weight (d − 35 + 1)² 7,396 2,116 0 121 27,556
Probability 20% 6% 0% 0.3% 74%

In this example (leaving aside the memory and exploration described below) the rover goes right three times out of four, but one time in five it tries the left: enough to avoid repeating the same lap.

2. Anti-repetition memory

The rover remembers which side it turned to last time and how many times in a row. Each repetition multiplies that side’s weight by 0.6: after two right turns the right side weighs 36% of normal. It is a minimal version of tabu search: it forbids nothing, but it discourages loops.

3. “Epsilon-greedy” exploration

With probability epsilon (5% to 35%, depending on the personality) the rover ignores the weights and picks a free direction at random. It is the same trade-off between exploiting what you know and exploring that is used in reinforcement learning.

4. A wandering path

While cruising, the two wheels don’t run at the same speed: the difference follows a wander value that changes a little at random every 100 ms but always tends back toward zero:

wander = wander - 0.15 * wander + wanderGain * 0.25 * gaussian()

This is an Ornstein-Uhlenbeck process, the discrete version of a spring immersed in noise: no nervous zig-zags, but smooth curves that are never the same. With wanderGain = 0 the rover drives straight.

5. Lévy flights: spontaneous turns

Even without obstacles, after a while the rover turns on its own by a random angle (60° on average). The length of each straight run is drawn from a Pareto distribution: many short runs and, now and then, a very long one. This is the Lévy flight strategy, observed in many foraging animals: mixing local exploration with long crossings covers an area much better than a uniform random walk. The levyAlpha parameter sets the character: the lower it is, the more frequent the long runs.

6. Curiosity pauses

Every now and then (on average every curiosityMs, with times drawn from an exponential distribution, like the events of a Poisson process) the rover stops, looks around and this time picks the most open direction without any randomness. From the outside it looks as if it “decides” where to go.

7. Small variations everywhere

Each turn lasts the theoretical time ±20%, reversing lasts 0.4 to 0.9 seconds, and the escape spin goes from 110° to 199°. These are small variations, but they are enough never to repeat exactly the same maneuver.

8. Personalities

All the parameters are grouped into three ready-made “personalities”. You choose one with a single line (Personality P = CURIOUS;) and you can create your own.

Parameter CALM CURIOUS NERVOUS
Cruise speed (PWM) 140 155 175
Stop distance 25 cm 25 cm 30 cm
Wandering (wanderGain) 0.15 0.35 0.60
Random exploration (epsilon) 5% 20% 35%
Shortest straight run (Lévy) 4 s 2 s 0.8 s
Curiosity pauses no about every 30 s about every 12 s

9. The random seed

Arduino’s random() produces the same sequence after every power-up unless you change its seed. The sketch reads the least significant bit of the unconnected pin A3, which picks up electrical noise, 32 times and mixes it with micros(). This way every power-up is different.

More ideas to try

  • Braitenberg vehicles: with two light sensors on the right and left, wired “crossed” or “straight” to the motor speeds, the rover seeks or flees the light. Surprisingly “emotional” behaviors with four lines of code.
  • A Markov chain of behaviors: instead of just two modes, a table of transition probabilities between exploring, following a wall, spinning in place and resting.
  • Wall following now and then: keeping the sonar at 70° and a constant distance from the wall, the rover explores the room’s perimeter, then goes back to wandering.
  • Subsumption architecture (Rodney Brooks): simple behaviors in layers, where safety behaviors (don’t crash, don’t fall) always take priority over exploration.

Settings to adjust

Parameter Value Effect
MAX_PWM 180 Motor speed limit. Don’t go above 200 with 6 V TT motors
SERVO_CENTER / SERVO_DIR 90 / 1 Center and direction of the head
LEFT_DIR / RIGHT_DIR 1 / 1 Direction of each wheel
LEFT_TRIM / RIGHT_TRIM 0 Compensation for driving straight
MS_PER_DEG 5.5 Milliseconds to rotate by one degree
MIN_FREE_CM 35 Below this distance a direction is not considered
HEAD_WOBBLE 12 Amplitude in degrees of the head sweep while cruising (0 = still). Helps spot obstacles slightly to the side, like chair legs
VBAT_MIN 6.6 V Voltage below which the rover stops
DEBUG true Messages on the Serial Monitor

Troubleshooting

Symptom Likely cause What to do
The Arduino resets when the motors or the servo start Voltage drops Check the 470 µF capacitor on the driver, that the servo is on the step-down and that the batteries are charged. With the UNO R3 it happens sooner when the batteries are low
The motors don’t move, everything else works STBY low or VM not connected Check A1 → STBY and the voltage on VM (it must be VBAT)
The sonar always reads 300 cm No echo: Trig and Echo swapped or no VCC Check the D10 → Trig and D11 → Echo wires and the 5 V on the sonar
The sonar reads random values Multiple echoes or soft surfaces Normal with sofas and curtains. The median helps; for better readings see the ToF sensors below
The servo jitters or hums Weak supply or the horn is rubbing Measure the step-down’s 5 V under load and check that the head turns freely
The rover turns the wrong way Motors or head reversed Repeat calibration steps 2 and 3
Turns are too short or too long MS_PER_DEG needs calibrating Measure the time of a full circle again
It stops and the board LED blinks Battery below 6.6 V Charge the cells. If it happens right away with charged batteries, check the divider
It reverses for no reason The “stuck” check fires by mistake It happens if the rover drives very slowly toward a distant wall: raise cruisePwm or the 2,500 ms time in doCruise()

Ideas for future upgrades

The rover is a platform: every extra sensor opens up new behaviors. Here are the upgrades that make the most sense, in order of difficulty.

Upgrade What you need What it adds Difficulty
Buzzer and status LED Passive buzzer, an RGB LED Sounds and expressions for each state: the rover “talks” Easy
Personality button A push button, the internal EEPROM Change character without re-uploading the sketch, and remember it after power-off Easy
Bumpers Two lever microswitches Detects the bumps the sonar can’t see (thin legs, low obstacles) Easy
Cliff sensors Two reflective IR sensors (TCRT5000) under the nose Stops at the edge of stairs Easy
Light sensors Two photoresistors (LDR) and two resistors Seeks or flees the light (Braitenberg vehicles): it was my 2012 plan for the second prototype Easy
Display 0.96″ I²C OLED, or the LED matrix of the UNO R4 WiFi Animated eyes, distances, battery voltage Medium
Wheel encoders The kit’s slotted discs and two optical fork sensors Precise turns in degrees instead of by time, automatic straight driving, distance traveled Medium
ToF distance sensors Two or three VL53L1X modules (I²C) Accurate readings even on soft surfaces and a wider field of view without a servo Medium
Compass and gyroscope 6- or 9-axis IMU module (I²C) Always knows where it is heading: exact turns and returning to a direction Medium
Remote control and telemetry UNO R4 WiFi (Wi-Fi and Bluetooth LE) Drive it from your phone, switch personalities, live distance charts Medium
Charging without disassembly 2S BMS module and 2S USB-C charger Cell protection and charging from a socket on the rover Medium
A map of the house An onboard computer (Arduino UNO Q or Raspberry Pi), a 2D LIDAR, ROS 2 Mapping and navigation to a chosen point Hard
Vision Arduino UNO Q with a webcam Recognizes objects or people with AI models running onboard Hard

About the last two: in October 2025 Arduino joined the Qualcomm group and launched the UNO Q, a board in the UNO form factor that combines an STM32 microcontroller with a processor running Linux. It is clearly overkill for avoiding obstacles, but for mapping and vision it is the natural next step after this project.

If you liked this project, take a look at Parolora, my ESP32 word clock, and at my first steps with Arduino in Hello world Arduino (in Italian). Questions, photos of your rover and name suggestions are welcome in the comments.

As an Amazon Associate I earn from qualifying purchases. Some links (Amazon and AliExpress) are affiliate links: they cost you nothing and help keep this blog running.