Robot vacuums and mop robots clean millions of floors every day while their owners are out. Inside, they are surprisingly simple: two wheels, a few sensors, a battery and a small computer that decides where to go next. In this capstone you build your own mop robot. A round, 3D-printed chassis carries two gear motors, the ESP32 and the L293D motor driver from your kit. Behind the wheels, a damp microfiber pad on a printed holder floats on the floor and wipes it as the robot drives. The ultrasonic sensor at the front sees walls and furniture coming, so the robot backs up and turns away by itself, and every few seconds it twists left and right to scrub. The ESP32 makes its own Wi-Fi network: on your phone you start a cleaning run, choose how long it cleans and how fast, or drive it by hand into a corner.
What you'll learn
- How a two-wheeled robot drives, turns on the spot and steers with an L293D
- How a state machine with millis() lets a robot back up, turn and scrub without blocking
- Why random turns are a simple but surprisingly good way to cover a room
- How to protect an ESP32 pin from a 5 V sensor with a voltage divider
- How to design a floating mop holder and a robot chassis for 3D printing
What you need
- ESP32 board, expansion board and USB cable (ESP32 IoT Starter Kit)
- L293D motor driver and a 100 µF capacitor (ESP32 IoT Starter Kit)
- Ultrasonic sensor HC-SR04 and 3 equal resistors between 1 kΩ and 10 kΩ, for example 3 × 1 kΩ (ESP32 IoT Starter Kit)
- Breadboard and jumper wires (ESP32 IoT Starter Kit)
- Two TT gear motors (3–6 V, the yellow ones) with 65 mm wheels, for example from a 2WD robot car chassis kit (not in the kit)
- A battery holder for 4 AA batteries with an on/off switch, and 4 AA alkaline batteries, for the motors (not in the kit). Rechargeable 1.2 V cells make the robot weak.
- A small USB power bank for the ESP32 (not in the kit)
- A microfiber cloth or a microfiber mop pad, and a strip of hook-and-loop tape
- 4 female-to-male jumper wires for the sensor, a few small cable ties, double-sided tape and two paper clips
- The printed parts from the 3D printing box below (chassis, deck, mop holder and sonar bracket), or the cardboard version described there
Safety: use the pad only damp, never wet. Wring the cloth out well: water must never drip onto the floor near the robot, and the breadboard, ESP32 and batteries must stay dry on top. Test on a hard floor (tiles, laminate, wood), not on carpet, and keep it away from stairs: an ultrasonic sensor doesn't see a drop. Switch the motor batteries off whenever you change the wiring, keep fingers away from the wheels, and don't leave it running alone near pets or small children.
Wiring
The breadboard has two supplies. The top rails carry 5 V from the ESP32's 5V pin (which comes from the power bank through the USB cable): they feed the L293D's logic and the ultrasonic sensor. The bottom rails carry the motor batteries, for the L293D's motor outputs. Only the two − rails are joined, never the + rails. The L293D's two enable pins are tied to 5 V, so both motors are always enabled; the ESP32 controls direction and speed through the four input pins.

Build it step by step
Plug in all the parts first, then add the wires in this order. In each picture the new wires are bright and the ones from earlier steps are faded. Click a picture to see it larger.






| From | To |
|---|---|
| ESP32 GPIO 25 | L293D pin 2 (IN1) |
| ESP32 GPIO 26 | L293D pin 7 (IN2) |
| ESP32 GPIO 32 | L293D pin 10 (IN3) |
| ESP32 GPIO 33 | L293D pin 15 (IN4) |
| L293D pins 3 and 6 (OUT1, OUT2) | Left motor |
| L293D pins 11 and 14 (OUT3, OUT4) | Right motor |
| L293D pin 16 (VCC1), pin 1 (EN1) and pin 9 (EN2) | Top + rail (5 V) |
| L293D pin 8 (VCC2) | Bottom + rail (motor batteries) |
| L293D pins 4, 5, 12 and 13 (GND) | The − rails |
| 100 µF capacitor | Across the bottom rails, the long leg (+) on + |
| HC-SR04 VCC and GND | ESP32 5V and the − rail |
| HC-SR04 Trig | ESP32 GPIO 13 |
| HC-SR04 Echo | Resistor R1 → ESP32 GPIO 27; R2 and R3 in a row from GPIO 27 to GND |
| ESP32 5V and GND | Top + rail and the − rail |
| 4 × AA battery holder: red, black | Bottom + rail, bottom − rail |
| Top − rail | Bottom − rail |
The HC-SR04 runs on 5 V and its Echo pin answers with 5 V, too much for the ESP32. The three equal resistors make a voltage divider: GPIO 27 sees two thirds of 5 V, about 3.3 V, as in the ultrasonic radar. Trig needs no protection, because there the ESP32 is the one sending.
If a wheel turns the wrong way later, swap that motor's two wires on the L293D. Build and test everything with the robot on a box, wheels in the air, before you put it on the floor. On the robot, the HC-SR04 sits on its bracket at the front: connect it to breadboard columns 12 to 15 with four female-to-male jumper wires.
Sensor modules from different makers can label and order their pins differently. Always follow the labels printed on your module.
Build this circuit in EEMENTOR Lab
Wire it yourself in your browser before you touch a real wire. No sign-up, nothing to install.
Build it yourself
- The ESP32 and this lesson’s parts are already placed. Wire them using the wiring table above. Pins with no wire show red.
- Missing a part? Add it from the parts list on the left.
- Press Run, then try the inputs: click, hold or slide them under Selected.
- Wi-Fi and Bluetooth don’t run in the Lab yet, so use it to build the circuit and check the wiring before you upload the real sketch.
EEMENTOR Lab is free and in beta. Results are a guide; a real build can differ slightly. About the Lab
The sketch
No extra libraries are needed: Wi-Fi and the web server come with the esp32 boards package. Choose Tools → Board → esp32 → ESP32 Dev Module. Change AP_PASSWORD to your own password of at least 8 characters.
// DIY mop robot: drives around the room with a damp mop pad behind it, turns away from walls
// and furniture, and wiggles now and then to scrub. Start, stop and steer it from your phone.
#include <WiFi.h>
#include <WebServer.h>
// ---------- settings ----------
const char* AP_NAME = "MopBot"; // the robot makes its own Wi-Fi network
const char* AP_PASSWORD = "change-me-123"; // at least 8 characters
const int STOP_CM = 18; // closer than this: back up and turn
const int SCRUB_EVERY_MS = 5000; // a scrubbing wiggle every 5 seconds
int speedPercent = 70; // driving speed, 50 to 100 (the page can change it)
int cleanMinutes = 10; // auto-clean time (the page can change it)
// ---------- pins ----------
const int LEFT_A = 25, LEFT_B = 26; // L293D pin 2 (IN1) and pin 7 (IN2): left motor
const int RIGHT_A = 32, RIGHT_B = 33; // L293D pin 10 (IN3) and pin 15 (IN4): right motor
const int TRIG = 13, ECHO = 27; // HC-SR04; Echo goes through the voltage divider
enum Mode { IDLE, FORWARD, BACKUP, TURN, SCRUB, MANUAL, BLOCKED };
const char* MODE_NAMES[] = {"Stopped", "Cleaning", "Backing up", "Turning", "Scrubbing", "Manual", "Blocked"};
Mode mode = IDLE;
unsigned long modeUntil = 0, cleanUntil = 0, nextScrub = 0, lastDrive = 0, lastMeasure = 0;
int turnDir = 1, scrubStep = 0, turnTries = 0, distanceCm = 999;
int manualL = 0, manualR = 0; // the arrow that is held on the phone
WebServer server(80);
const char PAGE[] = R"rawliteral(<!doctype html><html><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no"><title>MopBot</title>
<style>
body{margin:0;font-family:Arial,sans-serif;background:#F6F8FC;color:#1B3A7B;text-align:center;max-width:480px;margin:auto}
header{background:#1B3A7B;color:#fff;padding:12px;font-size:22px;font-weight:bold}
#st{margin:12px;padding:14px;border-radius:16px;background:#fff;box-shadow:0 2px 8px rgba(27,58,123,.08);font-size:22px;font-weight:bold}
#st small{display:block;font-size:14px;font-weight:normal;opacity:.7;margin-top:4px}
.row{display:flex;gap:10px;margin:10px 12px}
button{flex:1;font-size:18px;font-weight:bold;padding:16px 4px;border:0;border-radius:14px;background:#1B3A7B;color:#fff;touch-action:none;user-select:none}
button.go{background:#2E8B57} button.stop{background:#DE544A}
.pad{display:grid;grid-template-columns:repeat(3,1fr);gap:10px;margin:10px 12px}
.pad button{padding:22px 0;font-size:26px} .pad span{visibility:hidden}
label{display:block;margin:12px;font-size:15px} input,select{width:60%;font-size:16px}
</style></head><body>
<header>MopBot</header>
<div id="st">-<small></small></div>
<div class="row"><button class="go" onclick="go('/start')">Start cleaning</button><button class="stop" onclick="go('/stop')">Stop</button></div>
<p>Hold an arrow to drive by hand:</p>
<div class="pad"><span></span><button data-l="1" data-r="1">▲</button><span></span>
<button data-l="-1" data-r="1">◀</button><button data-l="-1" data-r="-1">▼</button><button data-l="1" data-r="-1">▶</button></div>
<label>Speed <input type="range" min="50" max="100" id="sp" onchange="go('/set?speed='+this.value)"></label>
<label>Clean for <select id="mi" onchange="go('/set?minutes='+this.value)"><option>5</option><option>10</option><option>15</option><option>20</option><option>30</option></select> minutes</label>
<script>
var held = null, timer = null;
function go(u) { return fetch(u).then(function (r) { return r.json(); }).then(show).catch(function () {}); }
function show(d) {
var st = document.getElementById('st');
st.firstChild.textContent = d.mode;
st.lastChild.textContent = 'Distance ahead: ' + (d.cm >= 999 ? 'far' : d.cm + ' cm') + (d.left > 0 ? ' · ' + Math.floor(d.left / 60) + ':' + ('0' + d.left % 60).slice(-2) + ' left' : '');
if (document.activeElement.id != 'sp') document.getElementById('sp').value = d.speed;
if (document.activeElement.id != 'mi') document.getElementById('mi').value = d.minutes;
}
function drive() { if (held) go('/drive?l=' + held.dataset.l + '&r=' + held.dataset.r); }
document.querySelectorAll('.pad button').forEach(function (b) {
b.onpointerdown = function (e) { e.preventDefault(); held = b; drive(); clearInterval(timer); timer = setInterval(drive, 200); };
b.onpointerup = b.onpointerleave = b.onpointercancel = function () { if (held == b) { held = null; clearInterval(timer); go('/drive?l=0&r=0'); } };
});
setInterval(function () { if (!held) go('/status'); }, 700);
go('/status');
</script></body></html>)rawliteral";
// ---------- motors ----------
// one motor: -100 (full backwards) to 100 (full forwards)
void motor(int pinA, int pinB, int power) {
int duty = map(abs(power), 0, 100, 0, 255);
if (power > 0) { analogWrite(pinA, duty); analogWrite(pinB, 0); }
else if (power < 0) { analogWrite(pinA, 0); analogWrite(pinB, duty); }
else { analogWrite(pinA, 0); analogWrite(pinB, 0); }
}
void drive(int left, int right) {
motor(LEFT_A, LEFT_B, left * speedPercent / 100);
motor(RIGHT_A, RIGHT_B, right * speedPercent / 100);
}
void setMode(Mode m, unsigned long ms) {
mode = m;
modeUntil = millis() + ms;
}
// ---------- the ultrasonic sensor ----------
int measureCm() {
digitalWrite(TRIG, LOW);
delayMicroseconds(2);
digitalWrite(TRIG, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG, LOW);
long us = pulseIn(ECHO, HIGH, 20000); // give up after 20 ms (about 3.4 m)
return us == 0 ? 999 : us / 58;
}
// ---------- auto-clean: what to do next ----------
void autoClean() {
unsigned long now = millis();
if (now >= cleanUntil) { drive(0, 0); mode = IDLE; return; } // time is up
switch (mode) {
case FORWARD:
if (distanceCm < STOP_CM) { // something ahead: back up first
drive(-100, -100);
setMode(BACKUP, 500);
} else if (now >= nextScrub) { // time for a scrubbing wiggle
scrubStep = 0;
setMode(SCRUB, 0);
} else {
drive(100, 100);
}
break;
case BACKUP:
if (now >= modeUntil) { // then turn a random amount, left or right
turnDir = random(2) ? 1 : -1;
turnTries = 0;
drive(100 * turnDir, -100 * turnDir);
setMode(TURN, random(350, 1100));
}
break;
case TURN:
if (now >= modeUntil) {
if (distanceCm < STOP_CM && ++turnTries < 8) setMode(TURN, 300); // still blocked: turn a little more
else if (distanceCm < STOP_CM) { drive(-100, -100); setMode(BACKUP, 500); } // stuck in a corner: back up again
else { drive(100, 100); setMode(FORWARD, 0); }
}
break;
case SCRUB: // left, right, left, right... six short twists
if (now >= modeUntil) {
if (scrubStep >= 6) {
nextScrub = now + SCRUB_EVERY_MS;
drive(100, 100);
setMode(FORWARD, 0);
} else {
int dir = scrubStep % 2 ? -1 : 1;
drive(100 * dir, -100 * dir);
scrubStep++;
setMode(SCRUB, 220);
}
}
break;
default:
break;
}
}
// ---------- web pages ----------
void sendStatus() {
long left = (mode != IDLE && mode != MANUAL && mode != BLOCKED && cleanUntil > millis()) ? (cleanUntil - millis()) / 1000 : 0;
String json = String("{\"mode\":\"") + MODE_NAMES[mode] + "\",\"cm\":" + distanceCm + ",\"left\":" + left +
",\"speed\":" + speedPercent + ",\"minutes\":" + cleanMinutes + "}";
server.send(200, "application/json", json);
}
void setup() {
Serial.begin(115200);
for (int p : {LEFT_A, LEFT_B, RIGHT_A, RIGHT_B}) pinMode(p, OUTPUT);
pinMode(TRIG, OUTPUT);
pinMode(ECHO, INPUT);
drive(0, 0);
WiFi.softAP(AP_NAME, AP_PASSWORD);
server.on("/", []() { server.send(200, "text/html", PAGE); });
server.on("/status", sendStatus);
server.on("/start", []() {
cleanUntil = millis() + cleanMinutes * 60000UL;
nextScrub = millis() + SCRUB_EVERY_MS;
drive(100, 100);
setMode(FORWARD, 0);
sendStatus();
});
server.on("/stop", []() { drive(0, 0); mode = IDLE; sendStatus(); });
server.on("/set", []() {
if (server.hasArg("speed")) speedPercent = constrain(server.arg("speed").toInt(), 50, 100);
if (server.hasArg("minutes")) cleanMinutes = constrain(server.arg("minutes").toInt(), 1, 60);
sendStatus();
});
server.on("/drive", []() { // hand driving: the page repeats this while an arrow is held
manualL = constrain(server.arg("l").toInt(), -1, 1);
manualR = constrain(server.arg("r").toInt(), -1, 1);
if (manualL == 0 && manualR == 0) { drive(0, 0); mode = IDLE; }
else { mode = MANUAL; lastDrive = millis(); }
sendStatus();
});
server.begin();
Serial.printf("Join the Wi-Fi \"%s\", then open http://", AP_NAME);
Serial.println(WiFi.softAPIP());
}
void loop() {
server.handleClient();
if (millis() - lastMeasure >= 60) { // measure the distance about 16 times a second
lastMeasure = millis();
distanceCm = measureCm();
}
if (mode == MANUAL || mode == BLOCKED) {
if (millis() - lastDrive > 500) { drive(0, 0); mode = IDLE; } // the phone stopped sending: stop
else if (manualL > 0 && manualR > 0 && distanceCm < STOP_CM) { drive(0, 0); mode = BLOCKED; } // never drive into things
else { drive(manualL * 100, manualR * 100); mode = MANUAL; }
} else if (mode != IDLE) {
autoClean();
}
}
Try it
- Put the robot on a box so the wheels are in the air. Upload the sketch, open the Serial Monitor at 115200 baud and note the Wi-Fi name and address.
- Switch on the motor batteries. On your phone, join the MopBot Wi-Fi with your password and open
http://192.168.4.1. The page shows "Stopped" and the distance ahead. - Hold the ▲ arrow: both wheels turn forwards. Try ◀ and ▶: the wheels turn in opposite directions, so the robot spins on the spot. If a wheel turns the wrong way, swap that motor's wires. Let go: the wheels stop.
- Hold your hand in front of the sensor and watch the distance. With your hand closer than 18 cm, ▲ stops the wheels and the page shows "Blocked": the robot won't drive into things.
- Wring out the microfiber pad well, press it onto the holder and put the robot on a hard floor. Choose 5 minutes and tap Start cleaning. It drives straight, stops before a wall, backs up, turns a random amount and drives on. Every 5 seconds it twists left and right a few times to scrub.
- Pressing an arrow during a cleaning run takes over (Manual); when you let go, the robot stops. Tap Start cleaning again to carry on. After the cleaning time it stops by itself and the page shows "Stopped". Look at the pad: the dust on it came off your floor. Try a different speed: slower is quieter and scrubs more, faster covers more floor.
What you should see

How it works

The robot drives like a tank. Each wheel has its own motor; when both turn forwards, it drives straight, and when they turn in opposite directions, it spins on the spot. The L293D has two H-bridges, one for each motor. For forwards, the sketch sends a PWM signal (fast on-off pulses) to one input of a motor and 0 to the other; for backwards it swaps them. The width of the pulses sets the speed: analogWrite(pin, 255) is full speed, 128 about half.
The brain is a state machine: the robot is always in exactly one state, Cleaning (driving forwards), Backing up, Turning or Scrubbing, and each state knows when it ends. When the sensor sees something closer than 18 cm, Cleaning switches to Backing up for half a second, then to Turning for a random time between 0.35 and 1.1 seconds, left or right. If the way is still blocked, it turns 0.3 seconds more, up to 8 times, and then backs up again, so it gets out of corners. Instead of delay(), each state remembers when it should end (modeUntil) and loop() checks the clock with millis(). That way the robot keeps measuring the distance 16 times a second and the web page keeps answering while it drives.
Why random turns? Without a map or wheel sensors, the robot doesn't know where it is. If it always turned the same amount, it could bounce between the same two walls forever. Random turns send it off in a new direction each time, and over a few minutes it reaches most of the room. The first robot vacuums worked almost exactly like this; newer ones add a map from a laser scanner or a camera so they can drive in neat lanes. The scrub wiggle rubs the pad back and forth over the same spot, like you do with a cloth on a sticky stain.
The mop holder floats: its pins slide freely in the sleeves, so the pad always rests on the floor with its own weight, even when the floor is a bit uneven, and it never lifts the wheels off the ground. The skid post at the front and the wheels carry the robot; the pad only adds its own weight, so it never lifts the wheels. When the robot spins on the spot, the pad swings around behind it like a tail and wipes a circle. Hand driving is safe as well: the page sends the arrow command again every 200 ms while you hold it, and if nothing arrives for half a second (you let go, or the Wi-Fi dropped), the robot stops by itself. While you hold ▲, the sketch checks the distance 16 times a second and stops the wheels as soon as something is closer than 18 cm.
Try this next
- Add a second ultrasonic sensor, pointing slightly left and right, so the robot can turn away from the side where the obstacle is instead of choosing randomly.
- Add a "spiral" mode for a dirty spot: start turning on the spot and slowly speed up the outer wheel, so the robot drives outwards in a growing spiral.
- Measure the battery: connect the motor battery through a voltage divider to an ESP32 analog pin, show the voltage on the page and stop cleaning when it gets low.
- Make it play a little tune on the piezo from the kit when it has finished cleaning, like real robot vacuums do.
- Print a small water tank with a cotton wick that keeps the pad damp. Test it carefully: a little moisture is enough, and no water may reach the electronics.
Troubleshooting
-
The page doesn't open: check that the phone is on the MopBot Wi-Fi (switch off mobile data for a moment) and type
http://192.168.4.1with http, not https. - The wheels don't turn at all: check that the motor batteries are switched on and connected to the bottom rails, and that the two − rails are joined. The L293D needs 5 V on pins 16, 1 and 9 as well.
- One wheel turns the wrong way: swap that motor's two wires on the L293D (pins 3 and 6 for the left motor, 11 and 14 for the right).
-
The robot drives in a curve instead of straight: cheap gear motors are never exactly the same. Make the faster side a little slower in
drive(), for exampleright * speedPercent / 100 * 90 / 100. -
It drives into walls: check the sensor's wires and the voltage divider (the distance on the page should change when you move your hand). Soft or slanted things, such as curtains or chair legs, reflect sound badly: make
STOP_CMbigger. - It is too weak to move with the pad: the pad is too wet or too heavy, or the batteries are low. Use fresh alkaline batteries (the L293D itself uses up about 2 V) and a thinner, well wrung-out cloth.
- The pad doesn't stay down on the floor: the pins stick in the sleeves. Sand them smooth, check that the paper clips don't catch, or tape a coin on top of the holder for a little more weight.
- The L293D gets hot: that is normal for a short time. If the robot is stuck against something with the wheels turning, stop it: the chip switches itself off when it gets too hot, and starts again when it has cooled down.
- The ESP32 restarts when the motors start: the ESP32 and the motors must have separate supplies (power bank and AA batteries). Check that the 100 µF capacitor is across the motor rails.
- A printed part is too tight or too loose: printers differ by a few tenths of a millimetre. Sand or file a tight hole, and fix a loose part with a drop of hot glue or a strip of tape.