Guides · 12 min read

ESP32-CAM Car: Build an FPV Robot Car with Live Video

Build an ESP32-CAM car: live video and direction buttons on one page, L298N PWM on the spare pins, a pin conflict table, brownout-proof power and a night flash.

An ESP32-CAM car is a robot car you drive while watching the live image from its front camera on your phone, the FPV (first-person view) way. A single ESP32-CAM board does three jobs at once: it creates its own Wi-Fi network, streams the OV2640 camera image to the browser and drives two wheels through an L298N motor driver using the four pins that are left. You don't need any app on your phone: type 192.168.4.1 in the browser and one page opens with the live video on top and forward, back, left, right and stop buttons below.

Because the ESP32-CAM has so few spare pins, this project needs more planning than an ordinary Wi-Fi car. In this guide we first build a pin conflict table showing which pins are taken by the camera, the SD card and the flash, then set up a power layout that feeds the motors and the camera from the same battery pack without brownout resets. Finally we walk line by line through ready-to-use code with speed control, a slider-controlled flash LED for night driving and a safety stop when the connection drops. The code compiles on both the 2.x and 3.x versions of the ESP32 Arduino core.

ESP32-CAM
ESP32-CAM
L298N
L298N
TT motor
TT motor
LM2596
LM2596

How does an ESP32-CAM car work?

There are four main parts. The ESP32-CAM is the camera, the brain and a small web server all in one, and it runs two separate servers: port 80 sends the control page and receives the short commands from the buttons, while port 81 is reserved for the video stream. The video is MJPEG: the camera compresses every frame as a JPEG, the ESP32 sends the frames one after another and the browser shows them like a video. Because the stream and the commands use different ports, a stop command is handled immediately even if the video stutters. The L298N is a dual H-bridge that turns the ESP32's 3.3 V signals into motor current. Two TT motors steer the car with differential drive: there's no steering axle, the car turns through the speed difference between the wheels. Two 18650 cells power the motors directly and the ESP32-CAM through a separate 5 V buck converter.

Parts list and cost

PartQtyApprox. price (USD)Note
AI-Thinker ESP32-CAM + ESP32-CAM-MB adapter16–10The MB adapter is only needed for programming
L298N motor driver module12–4The ENA and ENB jumpers stay on
2WD robot car chassis kit18–152 TT motors, 2 wheels and a caster wheel
18650 Li-ion cells and a 2-cell series holder2 + 17–14Branded cells rated for at least 5 A discharge
LM2596 buck converter module11–3A separate 5 V rail for the ESP32-CAM
1000 µF / 16 V and 100 nF capacitors1 + 2under 1For the ESP32-CAM supply and motor noise
Switch, jumper wires, double-sided tape-1–3To fix the camera to the front of the chassis
Total26–5010–18 if you already have cells and a chassis

The ESP32-CAM has no USB socket, so you need the ESP32-CAM-MB adapter or a USB-to-TTL converter to upload code; we covered the programming steps in detail in How to use the ESP32-CAM. We chose the L298N as the motor driver because it's available everywhere and reads the ESP32's 3.3 V signals without trouble. If you want a smaller, more efficient board, the L9110S works with the same four wires. Prices are typical online-shop averages and vary by country and shipping.

Pin conflicts: which ESP32-CAM pins are available?

The ESP32-CAM shows 16 pins along its edges, but the camera alone uses 15 GPIOs and none of them reach the header. Most of the GPIOs on the header are shared with the microSD slot. So the first decision is this: the car won't use the SD card. Without SD, GPIO 2, 4, 12, 13, 14 and 15 become available; we give four of them to the motors, GPIO 4 to the flash, and leave GPIO 2 unused. GPIO 1 and 3 are the serial port, so they stay reserved for uploading and the Serial Monitor. The table below lists each pin's normal job and how this project uses it; you can also look up the ESP32's general pin features in the Pinout tool.

PinNormal jobIn this projectWatch out
GPIO 0Camera clock (XCLK), boot modeCameraDon't touch; only tied to GND for uploading
GPIO 1 / 3Serial TX / RXUploading and Serial MonitorDon't use for motors
GPIO 2SD DATA0, strapping pinUnusedIf pulled HIGH during upload, the upload fails
GPIO 4SD DATA1 and flash LEDFlash (PWM)Full brightness for long heats the board
GPIO 12SD DATA2, strapping pin (MTDI)Right motor IN4If HIGH at boot, the board won't start
GPIO 13SD DATA3Right motor IN3The most reliable pin
GPIO 14SD CLKLeft motor IN1May output a short signal at boot
GPIO 15SD CMD, strapping pin (MTDO)Left motor IN2HIGH at boot through the internal pull-up
GPIO 16PSRAM-Don't touch
GPIO 33Red LED (on the back)-Not on the header; LOW turns it on
Never connect anything to GPIO 12 that pulls it HIGH at boot: this pin selects the flash memory voltage, and if it's HIGH the ESP32 switches to 1.8 V and won't start. The L298N inputs have no pull-up resistors, so this wiring is safe. Also, GPIO 14 and 15 output a short signal during boot, so the left motor may twitch for a moment at power-up; it's harmless, but keep the wheels off the ground during your first tests.

Wiring: ESP32-CAM, L298N and motors

L298N / powerESP32-CAMDescription
IN1GPIO 14Left motor forward input (PWM)
IN2GPIO 15Left motor reverse input (PWM)
IN3GPIO 13Right motor forward input (PWM)
IN4GPIO 12Right motor reverse input (PWM)
ENA / ENB-Jumpers stay on: both channels always enabled
+12V (VS)-Positive of the 2×18650 pack (after the switch)
GNDGNDBattery negative, LM2596 GND and ESP32-CAM GND at one point
LM2596 OUT+ (5.0 V)5VThe ESP32-CAM's only supply input; 1000 µF next to the board
OUT1 / OUT2-Left motor
OUT3 / OUT4-Right motor

In this wiring the speed is set directly on the IN pins instead of ENA and ENB. Going forward, IN1 gets PWM and IN2 stays LOW; going backward it's the other way round. During the off part of the PWM both inputs are LOW, so the L298N shorts the motor terminals and brakes, which gives more controlled driving at low speed. That's how four pins are enough instead of six. The L298N's logic inputs treat anything above 2.3 V as HIGH, so the ESP32-CAM's 3.3 V outputs connect without a level shifter. A fully charged pack gives 8.4 V; the L298N burns about 1.5–3 V of it and leaves the TT motors 5–6 V, their ideal range. We explained why all wires must meet at one GND point in GND and common ground.

Separate power and brownout prevention

The most common problem in ESP32-CAM cars isn't the code, it's the power supply. While streaming over Wi-Fi the board draws 180–250 mA on average at 5 V; with the flash on it goes past 300 mA, and the Wi-Fi transmitter's short peaks are even higher. Two TT motors can pull 1.5–2 A together when they start. If the motors and the board share the same weak supply, the voltage collapses for a moment at every start, the Serial Monitor prints Brownout detector was triggered and the board reboots; the car stalls mid-drive and the video freezes. The fix is to keep the motor current away from the ESP32-CAM's supply:

Power optionProsConsVerdict
ESP32-CAM from the L298N's 5V outputNo extra partsThe onboard 78M05 gives about 0.5 A at most and sags when the motors startNot recommended: frequent brownouts
Same pack + LM2596 (5.0 V) + 1000 µFOne battery, stable 5 V, up to 2 ABelow about 6.5 V the converter can't hold 5 VRecommended
Separate source: 2×18650 for the motors, a power bank or 18650 + 5 V boost for the boardMotor noise never reaches the boardExtra weight and a second chargeCleanest video
  • Capacitor: Fit a 1000 µF / 16 V electrolytic capacitor between the ESP32-CAM's 5V and GND pins, as close to the board as possible (positive lead to 5V). Solder a 100 nF ceramic capacitor across each motor's terminals too.
  • Set the LM2596 first: Before connecting it to the board, adjust the output to 5.0–5.1 V with a multimeter; it often ships set close to the input voltage and can kill the ESP32-CAM instantly.
  • Short, thick wires: Use short, thick wires for power instead of a breadboard and thin jumpers; even a 20 cm thin jumper causes a noticeable voltage drop at 300 mA.
  • Common GND: The battery negative, L298N, LM2596 and ESP32-CAM GND must meet at one point; otherwise the motor commands behave randomly.
  • Don't disable brownout in code: The WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0) line hides the resets but doesn't fix the voltage drop; the board then freezes or produces corrupted frames instead. Details are in ESP32 brownout and Guru Meditation.

Step-by-step setup

  1. In the Arduino IDE install the esp32 by Espressif Systems package, select AI Thinker ESP32-CAM as the board and leave the Partition Scheme on Huge APP.
  2. Screw the motors to the chassis; connect the left motor to the L298N's OUT1-OUT2 terminals and the right motor to OUT3-OUT4. Leave the ENA and ENB jumpers in place.
  3. Set the LM2596 output to 5.0 V with a multimeter, then connect it to the ESP32-CAM's 5V and GND pins and add the 1000 µF capacitor.
  4. Connect the four signal wires from the table (GPIO 14, 15, 13, 12) and the common GND. Remove the microSD card from the slot.
  5. Plug the ESP32-CAM into the MB adapter and upload the motor test code; check the direction of each wheel with the wheels in the air.
  6. Upload the main code, move the board from the adapter to the chassis and fix the camera at the front with the lens facing the driving direction.
  7. In your phone's Wi-Fi settings connect to BlueGrays-CAM-Car with the password 12345678 and type 192.168.4.1 in the browser.
  8. Once the video shows up, drive by holding the buttons; when you lift your finger, the car stops.

Test the motors first

Before bringing in the camera and Wi-Fi, check your wiring with this short sketch. It drives the motors at full speed forward for one second, backward for one second, then spins the car left and right on the spot. If a wheel turns backward during the forward step, don't change the code; swap that motor's two wires on the L298N. If nothing turns, check the battery switch, the common GND and whether the ENA-ENB jumpers are on.

C++ (Arduino IDE)
1// ESP32-CAM + L298N motor testi (kamera ve Wi-Fi yok) / motor test (no camera, no Wi-Fi)
2// Sol motor / left motor: IN1=14, IN2=15 — Sağ motor / right motor: IN3=13, IN4=12
3const int L_IN1 = 14, L_IN2 = 15;
4const int R_IN3 = 13, R_IN4 = 12;
5
6void wheels(int a, int b, int c, int d) {
7  digitalWrite(L_IN1, a); digitalWrite(L_IN2, b);
8  digitalWrite(R_IN3, c); digitalWrite(R_IN4, d);
9}
10
11void setup() {
12  int pins[] = {L_IN1, L_IN2, R_IN3, R_IN4};
13  for (int p : pins) pinMode(p, OUTPUT);
14  wheels(LOW, LOW, LOW, LOW);
15  delay(3000);                                 // tekerlekleri havaya kaldır / lift the wheels
16}
17
18void loop() {
19  wheels(HIGH, LOW, HIGH, LOW); delay(1000);   // ileri / forward
20  wheels(LOW, LOW, LOW, LOW);   delay(500);    // dur / stop
21  wheels(LOW, HIGH, LOW, HIGH); delay(1000);   // geri / backward
22  wheels(LOW, LOW, LOW, LOW);   delay(500);
23  wheels(LOW, HIGH, HIGH, LOW); delay(600);    // yerinde sola / spin left
24  wheels(HIGH, LOW, LOW, HIGH); delay(600);    // yerinde sağa / spin right
25  wheels(LOW, LOW, LOW, LOW);   delay(2000);
26}

Main code: live video and direction buttons on one page

The main program needs no libraries other than esp_camera, esp_http_server and WiFi, which come with the ESP32 package. The control page is embedded in the code as a single string of HTML, CSS and JavaScript. When the page opens, the video box connects itself to the /stream feed on port 81. While you hold a button, the browser sends a small command such as /go?d=f&s=70 every 150 ms; the letter d carries the direction (f forward, b back, l left, r right, s stop) and the number s carries the speed in percent. When you release the flash slider, a request such as /led?v=120 sets the flash brightness.

C++ (Arduino IDE)
1#include "esp_camera.h"
2#include "esp_http_server.h"
3#include <WiFi.h>
4
5const char* AP_SSID = "BlueGrays-CAM-Car";   // telefonda görünecek ağ adı / network name on the phone
6const char* AP_PASS = "12345678";            // en az 8 karakter / at least 8 characters
7
8// AI-Thinker ESP32-CAM kamera pinleri / AI-Thinker ESP32-CAM camera pins
9#define PWDN_GPIO_NUM     32
10#define RESET_GPIO_NUM    -1
11#define XCLK_GPIO_NUM      0
12#define SIOD_GPIO_NUM     26
13#define SIOC_GPIO_NUM     27
14#define Y9_GPIO_NUM       35
15#define Y8_GPIO_NUM       34
16#define Y7_GPIO_NUM       39
17#define Y6_GPIO_NUM       36
18#define Y5_GPIO_NUM       21
19#define Y4_GPIO_NUM       19
20#define Y3_GPIO_NUM       18
21#define Y2_GPIO_NUM        5
22#define VSYNC_GPIO_NUM    25
23#define HREF_GPIO_NUM     23
24#define PCLK_GPIO_NUM     22
25
26// Kalan pinler (SD kart kullanılmıyor) / remaining pins (SD card not used)
27const int L_IN1 = 14, L_IN2 = 15;            // sol motor -> L298N IN1, IN2 / left motor
28const int R_IN3 = 13, R_IN4 = 12;            // sağ motor -> L298N IN3, IN4 / right motor
29const int FLASH_PIN = 4;                     // beyaz flaş LED'i / white flash LED
30const int PWM_PINS[5] = {L_IN1, L_IN2, R_IN3, R_IN4, FLASH_PIN};
31
32const int PWM_FREQ = 1000;                   // Hz
33const int PWM_RES = 8;                       // 8 bit: 0-255
34const int MIN_DUTY = 100;                    // motorun kalktığı en düşük değer / lowest duty that moves the motor
35const unsigned long FAILSAFE_MS = 600;       // bu süre komut gelmezse dur / stop if no command for this long
36
37volatile char cmdDir = 's';                  // f, b, l, r, s
38volatile int cmdSpeed = 70;                  // yüzde / percent
39volatile unsigned long lastCmd = 0;
40
41httpd_handle_t ctrlServer = NULL;            // port 80: sayfa ve komutlar / page and commands
42httpd_handle_t streamServer = NULL;          // port 81: canlı görüntü / live video
43
44const char PAGE[] = R"rawliteral(
45<!DOCTYPE html><html><head><meta charset="utf-8">
46<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no">
47<title>BlueGrays CAM Car</title>
48<style>
49body{margin:0;background:#0f172a;color:#e2e8f0;font-family:sans-serif;text-align:center;user-select:none;-webkit-user-select:none}
50img{width:100%;max-width:640px;background:#000;display:block;margin:0 auto}
51.pad{display:grid;grid-template-columns:repeat(3,90px);gap:8px;justify-content:center;margin:14px}
52button{height:70px;border:0;border-radius:14px;background:#1e293b;color:#e2e8f0;font-size:16px;touch-action:none}
53button:active{background:#38bdf8;color:#0f172a}
54label{display:block;margin:8px}
55</style></head><body>
56<img id="cam" alt="camera">
57<div class="pad">
58<span></span><button data-d="f">Forward</button><span></span>
59<button data-d="l">Left</button><button data-d="s">Stop</button><button data-d="r">Right</button>
60<span></span><button data-d="b">Back</button><span></span>
61</div>
62<label>Speed <input id="sp" type="range" min="40" max="100" value="70"></label>
63<label>Flash <input id="fl" type="range" min="0" max="255" value="0"></label>
64<script>
65document.getElementById('cam').src='http://'+location.hostname+':81/stream';
66let dir='s',busy=false;
67function send(){if(busy)return;busy=true;
68 fetch('/go?d='+dir+'&s='+document.getElementById('sp').value).catch(()=>{}).finally(()=>{busy=false;});}
69document.querySelectorAll('button').forEach(b=>{
70 b.addEventListener('pointerdown',e=>{dir=b.dataset.d;send();e.preventDefault();});
71 ['pointerup','pointerleave','pointercancel'].forEach(t=>b.addEventListener(t,()=>{dir='s';send();}));
72});
73document.addEventListener('contextmenu',e=>e.preventDefault());
74setInterval(send,150);
75document.getElementById('fl').addEventListener('change',e=>fetch('/led?v='+e.target.value));
76</script></body></html>
77)rawliteral";
78
79// PWM: 2.x'te kanal 0-4 kullanılır, kamera kanal 7 / zamanlayıcı 3'te kalır
80// PWM: 2.x uses channels 0-4, the camera stays on channel 7 / timer 3
81void pwmBegin() {
82  for (int i = 0; i < 5; i++) {
83#if ESP_ARDUINO_VERSION_MAJOR >= 3
84    ledcAttach(PWM_PINS[i], PWM_FREQ, PWM_RES);
85#else
86    ledcSetup(i, PWM_FREQ, PWM_RES);
87    ledcAttachPin(PWM_PINS[i], i);
88#endif
89  }
90}
91
92void setDuty(int index, int duty) {
93#if ESP_ARDUINO_VERSION_MAJOR >= 3
94  ledcWrite(PWM_PINS[index], duty);           // 3.x: pin numarasıyla / by pin number
95#else
96  ledcWrite(index, duty);                     // 2.x: kanal numarasıyla / by channel number
97#endif
98}
99
100// index 0 = sol, 2 = sağ; speed -100 … 100 / index 0 = left, 2 = right
101void motor(int index, int speed) {
102  int duty = (speed == 0) ? 0 : map(abs(speed), 1, 100, MIN_DUTY, 255);
103  setDuty(index,     speed > 0 ? duty : 0);   // ileri girişi / forward input
104  setDuty(index + 1, speed < 0 ? duty : 0);   // geri girişi / reverse input
105}
106
107void drive(char dir, int sp) {
108  int turn = sp * 7 / 10;                     // dönüşte %70 hız / 70% speed while turning
109  switch (dir) {
110    case 'f': motor(0, sp);     motor(2, sp);     break;
111    case 'b': motor(0, -sp);    motor(2, -sp);    break;
112    case 'l': motor(0, -turn);  motor(2, turn);   break;
113    case 'r': motor(0, turn);   motor(2, -turn);  break;
114    default:  motor(0, 0);      motor(2, 0);
115  }
116}
117
118bool cameraBegin() {
119  camera_config_t c = {};
120  c.ledc_channel = LEDC_CHANNEL_7;            // motor PWM'iyle çakışmasın / keep clear of motor PWM
121  c.ledc_timer   = LEDC_TIMER_3;
122  c.pin_d0 = Y2_GPIO_NUM;  c.pin_d1 = Y3_GPIO_NUM;
123  c.pin_d2 = Y4_GPIO_NUM;  c.pin_d3 = Y5_GPIO_NUM;
124  c.pin_d4 = Y6_GPIO_NUM;  c.pin_d5 = Y7_GPIO_NUM;
125  c.pin_d6 = Y8_GPIO_NUM;  c.pin_d7 = Y9_GPIO_NUM;
126  c.pin_xclk = XCLK_GPIO_NUM;    c.pin_pclk = PCLK_GPIO_NUM;
127  c.pin_vsync = VSYNC_GPIO_NUM;  c.pin_href = HREF_GPIO_NUM;
128  c.pin_sccb_sda = SIOD_GPIO_NUM; c.pin_sccb_scl = SIOC_GPIO_NUM;
129  c.pin_pwdn = PWDN_GPIO_NUM;    c.pin_reset = RESET_GPIO_NUM;
130  c.xclk_freq_hz = 20000000;
131  c.pixel_format = PIXFORMAT_JPEG;
132  c.frame_size = FRAMESIZE_QVGA;              // 320x240: akıcı ve düşük gecikme / smooth, low latency
133  c.jpeg_quality = 12;                        // 0-63, küçük = kaliteli / lower = better
134  if (psramFound()) {
135    c.fb_count = 2;
136    c.fb_location = CAMERA_FB_IN_PSRAM;
137    c.grab_mode = CAMERA_GRAB_LATEST;         // hep en yeni kare / always the newest frame
138  } else {
139    c.fb_count = 1;
140    c.fb_location = CAMERA_FB_IN_DRAM;
141    c.grab_mode = CAMERA_GRAB_WHEN_EMPTY;
142  }
143  if (esp_camera_init(&c) != ESP_OK) return false;
144  sensor_t* s = esp_camera_sensor_get();
145  s->set_vflip(s, 1);                         // kamera ters takılıysa / camera mounted upside down
146  s->set_hmirror(s, 1);
147  return true;
148}
149
150static esp_err_t indexHandler(httpd_req_t* req) {
151  httpd_resp_set_type(req, "text/html");
152  return httpd_resp_send(req, PAGE, HTTPD_RESP_USE_STRLEN);
153}
154
155static esp_err_t goHandler(httpd_req_t* req) {    // /go?d=f&s=70
156  char q[40], v[8];
157  if (httpd_req_get_url_query_str(req, q, sizeof(q)) == ESP_OK) {
158    if (httpd_query_key_value(q, "d", v, sizeof(v)) == ESP_OK) cmdDir = v[0];
159    if (httpd_query_key_value(q, "s", v, sizeof(v)) == ESP_OK) cmdSpeed = constrain(atoi(v), 0, 100);
160  }
161  lastCmd = millis();
162  return httpd_resp_send(req, "ok", HTTPD_RESP_USE_STRLEN);
163}
164
165static esp_err_t ledHandler(httpd_req_t* req) {   // /led?v=0-255
166  char q[20], v[6];
167  if (httpd_req_get_url_query_str(req, q, sizeof(q)) == ESP_OK &&
168      httpd_query_key_value(q, "v", v, sizeof(v)) == ESP_OK) {
169    setDuty(4, constrain(atoi(v), 0, 255));
170  }
171  return httpd_resp_send(req, "ok", HTTPD_RESP_USE_STRLEN);
172}
173
174#define BOUNDARY "bluegraysframe"
175static esp_err_t streamHandler(httpd_req_t* req) { // MJPEG: kareleri art arda gönderir / sends frames back to back
176  char head[96];
177  httpd_resp_set_type(req, "multipart/x-mixed-replace;boundary=" BOUNDARY);
178  while (true) {
179    camera_fb_t* fb = esp_camera_fb_get();
180    if (!fb) return ESP_FAIL;
181    int n = snprintf(head, sizeof(head),
182                     "\r\n--" BOUNDARY "\r\nContent-Type: image/jpeg\r\nContent-Length: %u\r\n\r\n",
183                     (unsigned)fb->len);
184    esp_err_t res = httpd_resp_send_chunk(req, head, n);
185    if (res == ESP_OK) res = httpd_resp_send_chunk(req, (const char*)fb->buf, fb->len);
186    esp_camera_fb_return(fb);
187    if (res != ESP_OK) return res;            // tarayıcı kapandı / browser closed
188  }
189}
190
191void addUri(httpd_handle_t srv, const char* uri, esp_err_t (*fn)(httpd_req_t*)) {
192  httpd_uri_t u = {};
193  u.uri = uri;
194  u.method = HTTP_GET;
195  u.handler = fn;
196  httpd_register_uri_handler(srv, &u);
197}
198
199void startServers() {
200  httpd_config_t cfg = HTTPD_DEFAULT_CONFIG();
201  cfg.server_port = 80;
202  if (httpd_start(&ctrlServer, &cfg) == ESP_OK) {
203    addUri(ctrlServer, "/", indexHandler);
204    addUri(ctrlServer, "/go", goHandler);
205    addUri(ctrlServer, "/led", ledHandler);
206  }
207  cfg.server_port = 81;
208  cfg.ctrl_port += 1;                         // her sunucuya ayrı kontrol portu / own control port per server
209  if (httpd_start(&streamServer, &cfg) == ESP_OK) {
210    addUri(streamServer, "/stream", streamHandler);
211  }
212}
213
214void setup() {
215  Serial.begin(115200);
216  pwmBegin();
217  drive('s', 0);
218  if (!cameraBegin()) Serial.println("Kamera baslatilamadi / Camera init failed");
219  WiFi.softAP(AP_SSID, AP_PASS);              // kendi Wi-Fi ağını kurar / creates its own Wi-Fi network
220  startServers();
221  Serial.print("Adres / address: http://");
222  Serial.println(WiFi.softAPIP());            // 192.168.4.1
223}
224
225void loop() {
226  static char lastDir = 0;
227  static int lastSpeed = -1;
228  if (millis() - lastCmd > FAILSAFE_MS) cmdDir = 's';   // bağlantı koptu: dur / link lost: stop
229  char d = cmdDir;
230  int sp = cmdSpeed;
231  if (d != lastDir || sp != lastSpeed) {
232    drive(d, sp);
233    lastDir = d;
234    lastSpeed = sp;
235  }
236  delay(10);
237}
CodeWhat it does
c.ledc_channel = LEDC_CHANNEL_7Moves the camera clock to PWM channel 7 and timer 3; motor and flash PWM stay on channels 0–4
FRAMESIZE_QVGA, jpeg_quality 12320×240 resolution: small frames travel fast and latency stays low
CAMERA_GRAB_LATESTAlways sends the newest frame instead of an old one waiting in the buffer
httpd_start (ports 80 and 81)Page and commands run on a different server from the video stream; the stream never blocks the commands
streamHandlerSends frames back to back as multipart/x-mixed-replace; leaves the loop when the browser closes
motor(index, speed)Puts PWM on the forward or reverse input depending on the sign of the speed and sets the other to 0
map(abs(speed), 1, 100, MIN_DUTY, 255)Starts even the lowest speed at the PWM value where the motor actually moves
millis() - lastCmd > FAILSAFE_MSStops the car if no command arrives for 600 ms

The most important detail in the code is the PWM channels. On the ESP32, the same hardware block, LEDC, generates both the motor speed and the camera's 20 MHz clock signal. The stock camera examples put the camera on channel 0 and timer 0; if you also open channel 0 for the motors, the timer is reset to 1 kHz, the camera clock breaks and no image arrives. That's why we moved the camera to channel 7 and timer 3. In ESP32 core 2.x the motors and the flash use channels 0–4 chosen by the code, and in 3.x they use the first unused channels handed out in order by ledcAttach; either way there's no clash with the camera. The #if ESP_ARDUINO_VERSION_MAJOR >= 3 lines also pick the right PWM functions, which changed in 3.x. For PWM basics, see What is PWM.

Does the car stop when the connection drops?

The most dangerous moment for a Wi-Fi-driven car is when the signal drops: the phone screen locks, the browser goes to the background or the car leaves the range. In this code the page sends a command every 150 ms even when you aren't pressing anything; with no button held, that command is "stop". The ESP32 stores the time of each command in lastCmd, and on every pass loop() checks how old the last command is. If nothing arrives for 600 ms, about four commands in a row, the direction is forced to "stop". Commands are received in the web server's own task, but only loop() touches the motors, so two tasks never write PWM at the same time. The busy flag in the browser also stops requests from piling up when the network slows down, so an old, delayed command is never applied later.

Night driving: setting the flash LED with a slider

The white LED on the front of the ESP32-CAM is driven by a transistor connected to GPIO 4; the pin itself only switches the transistor. Since we don't use the SD card, we can put PWM on this pin and set the brightness from 0 to 255. In a dark room a value between 60 and 120 lights up a few metres ahead and clearly reduces the noise in the image. At full brightness the LED draws more than 100 mA extra and warms the board within a few minutes, so stay below half brightness on long drives. The camera's auto exposure needs a second or two to adapt to the new light, so it's normal for the image to flare up right after you turn the flash on and then settle. You can also build real night vision with an OV2640 lens without an infrared filter and infrared LEDs; daytime colours will look washed out in that case.

Resolution, latency and range

ResolutionPixelsApprox. FPS (softAP)For driving
QQVGA160×12025–30Very smooth but little detail
QVGA (in the code)320×24020–25Best balance, recommended
CIF400×29615–20Usable with a good signal
VGA640×48010–15Lag becomes noticeable
SVGA800×6006–10Too slow for driving, good for photos

Most of the time the frame rate is limited by Wi-Fi, not by the camera: as resolution and quality go up, each JPEG frame grows and crosses the network more slowly. For driving, what matters isn't just the frame rate but how far behind the image arrives; at QVGA this latency is usually around 150–250 ms, which is comfortable for manual driving. The ESP32-CAM's small PCB antenna is weaker than that of regular ESP32 boards; expect 20–40 m in the open and about 10 m indoors through a wall or two. For longer range you can fit an external antenna to the IPEX connector and move the 0 Ω resistor next to it. If you drive the car at home and want to stay online at the same time, you can also connect the ESP32-CAM to your router; in setup(), replace the WiFi.softAP line with the snippet below and open the address shown in the Serial Monitor.

C++ (Arduino IDE)
1// setup() içinde WiFi.softAP(...) satırının yerine / in setup(), instead of the WiFi.softAP(...) line
2WiFi.mode(WIFI_STA);
3WiFi.begin("EvAgim", "sifre123");          // ev ağının adı ve şifresi / your home network name and password
4while (WiFi.status() != WL_CONNECTED) delay(300);
5WiFi.setSleep(false);                      // modem uykusunu kapat, gecikme düşer / disable modem sleep, lower latency
6Serial.println(WiFi.localIP());            // tarayıcıya bu adresi yaz / type this address in the browser

Common problems and fixes

SymptomLikely causeFix
The board resets and the video freezes when the motors startThe supply collapses (brownout)Power the ESP32-CAM from an LM2596 or a separate source, add 1000 µF, use good 18650 cells
Black image, frame errors in the Serial MonitorThe camera clock clashes with a motor PWM channelMove the camera to LEDC_CHANNEL_7 / LEDC_TIMER_3
Camera init failed 0x105Camera not found: ribbon cable or pin definitionsReseat the ribbon cable and make sure you use the AI-Thinker pins
Upload fails (Failed to connect)Something on GPIO 2 or 12 upsets the boot modeUnplug the motor wires and the SD card while uploading, tie IO0 to GND
The car won't move at low speedPWM value below the start thresholdRaise MIN_DUTY to 120–140
One wheel turns the wrong wayMotor wires reversedSwap that motor's two wires on the L298N
Image upside down or mirroredCamera mounted in a different orientationSet set_vflip and set_hmirror to 0 or 1
Video lags a lotResolution too high or weak signalGo back to QVGA, keep the antenna away from metal, change the Wi-Fi channel
To check the video and the commands separately, first open only http://192.168.4.1:81/stream in the browser. If the stream is smooth there, the problem is in the page or the motors; if it stutters there too, look at the power supply, the antenna or the resolution. The stream server serves one viewer at a time: if you open a second tab, it stays blank until the first stream closes.

Ideas to upgrade your car

  • Collision brake: Mount a single-output infrared obstacle sensor at the front, power it from 3.3 V, wire its output to the spare GPIO 2 and ignore forward commands when it sees an obstacle; unplug that wire while uploading. To choose a sensor, read the distance sensor comparison.
  • Photo button: Add a button to the page and an address that returns a single JPEG frame; to send the photo to Telegram, combine it with the code from ESP32-CAM Telegram.
  • Joystick control: Use the joystick page from the ESP32 Wi-Fi car instead of buttons; its left and right speed values can go straight into the motor() function.
  • Wireless updates: Switch the Partition Scheme to one with OTA support and use ESP32 OTA to upload new code without plugging the board into the adapter every time.
  • Physical remote: Send commands from a second ESP32 with a joystick module over ESP-NOW and watch the video on your phone.

An ESP32-CAM car is a small but very instructive build that teaches camera handling, web servers, PWM and power design in one project. The pin plan and power separation you set up here will help you in every ESP32-CAM project you build later. You'll find the camera itself and its programming steps in How to use the ESP32-CAM, and the joystick version without a camera in ESP32 Wi-Fi car. In the BlueGrays app you can also explore the L298N Bluetooth-controlled car, the obstacle-avoiding robot and ESP32 web server projects with step-by-step circuit diagrams and code.

Frequently asked questions

Can you build a robot car with an ESP32-CAM, and which pins drive the motors?

Yes. If you don't use the SD card, GPIO 12, 13, 14 and 15 are available for the motor driver's four inputs and GPIO 4 for the flash. Speed is controlled by putting PWM on those four pins, so you don't need extra GPIOs for the L298N's ENA and ENB pins.

Does an ESP32-CAM car work without internet?

Yes. In softAP mode the ESP32-CAM creates its own Wi-Fi network and the phone connects straight to it; video and commands travel over that local network. If the phone warns that there's no internet, choose to stay connected and turn off mobile data if needed.

Why does my ESP32-CAM reset when the motors start?

The motors' start-up current pulls the supply voltage down for a moment, and the ESP32 sees it as a brownout and reboots. Power the ESP32-CAM from a separate 5 V buck converter (LM2596) or a separate source instead of the L298N's 5V output, and add a 1000 µF capacitor next to the board.

Can I use the SD card and the motors at the same time on an ESP32-CAM?

Not easily with direct pins, because GPIO 12–15, which drive the motors, are also the SD card lines. Starting the SD card in 1-bit mode releases GPIO 4, 12 and 13, but two motors need four pins. In that case, handing the motors to a second microcontroller that takes commands over serial is the cleaner solution.

What range and video latency does an ESP32-CAM car have?

With the small onboard antenna, expect about 20–40 m in the open and around 10 m indoors; an external antenna increases that noticeably. At 320×240 the video arrives about 150–250 ms late, which is enough for manual driving.

L298N or L9110S for an ESP32-CAM car?

Both work with the same four wires and accept the ESP32-CAM's 3.3 V signals. The L298N is everywhere and more than strong enough for TT motors, but it loses 1.5–3 V and gets warm. The L9110S is smaller, lighter and more efficient; at about 800 mA per channel it's enough for two TT motors.

See all projects
Bluetooth Controlled Car with L298N
AR-80Advanced
Premium

Bluetooth Controlled Car with L298N

Turn your phone into a remote and drive your own robot car. The Arduino receives commands from a remote-control app on your phone through a Bluetooth module and spins the wheels with a motor driver…

5.0(39)
66
Obstacle Avoidance Robot
AR-81Advanced
Premium

Obstacle Avoidance Robot

How about building a smart vehicle that finds its own way? The Obstacle Avoidance Robot constantly scans its surroundings thanks to the ultrasonic sensor in front of it.

5.0(38)
49
ESP32 Asynchronous Web Server (with IP Display on LCD)
ES-27Advanced

ESP32 Asynchronous Web Server (with IP Display on LCD)

In this project, we’re turning the ESP32 into an asynchronous web server that you can control from your phone or computer on the same Wi-Fi network. Thanks to the ESPAsyncWebServer library, the server can process multiple requests simultaneously (unlike the classic WebServer.h, which blocks on a single request). You’ll be able to open the ESP32’s IP address in a browser and click the ON/OFF buttons (the /on and /off routes) to turn the LED connected to GPIO 5 on and off.

4.8(16)
27
ESP32 WebSocket Counter (2 Buttons + LCD + Real-Time Web)
ES-28Advanced
Premium

ESP32 WebSocket Counter (2 Buttons + LCD + Real-Time Web)

In this project, two buttons wired to the ESP32 (GPIO 5 counts up, GPIO 4 counts down) change a counter. The value updates instantly both on a 16x2 I2C LCD and, through the WebSocket support of ESPAsyncWebServer, in every connected browser without reloading the page. Instead of HTTP polling a single persistent connection is used, and the ESP32 sends the new value to everyone with ws.textAll().

4.5(14)
23
ESP32 Wi-Fi STA Connection (with LCD Screen)
ES-25Advanced

ESP32 Wi-Fi STA Connection (with LCD Screen)

In this project, we connect the ESP32 to the home Wi-Fi network in Station (STA) mode in a secure, fault-tolerant manner. We store the SSID and password in a separate secrets.h file to prevent leaking to Git, set up an auto-reconnect mechanism, and display the RSSI signal level and IP address on an I2C LCD screen. The internal LED works as a status indicator. It is a production-grade connection manager.

4.4(21)
41
ESP32 LED Fade with PWM
ES-8Beginner

ESP32 LED Fade with PWM

Smoothly changing the brightness of the LED from 0 to max, from max to 0. We control PWM with analogWrite() as in Arduino - the same syntax as ESP32 Arduino Core 3.0+ works without problems. Pin definition + pinMode + analogWrite is enough.

4.8(36)
55
ESP32 OTA Update — Wireless Firmware Installation (With LCD Screen)
ES-30Advanced
Premium

ESP32 OTA Update — Wireless Firmware Installation (With LCD Screen)

In this project you'll learn to upload new firmware to the ESP32 over Wi-Fi, without a USB cable. With the ArduinoOTA library the ESP32 becomes visible on the network and shows up automatically as bluegrays-ota under "Network port" in the Arduino IDE. The first upload goes over USB; after that every update is wireless, a key feature for devices out in the field.

4.6(14)
22
ESP32 mDNS: Accessing the Device via bluegrays-esp.local (with LCD Screen)
ES-29Advanced
Premium

ESP32 mDNS: Accessing the Device via bluegrays-esp.local (with LCD Screen)

In this project we add an mDNS (Multicast DNS) service to the ESP32, so you reach it by a readable host name like bluegrays-esp.local instead of an IP address. Even if the IP assigned by DHCP changes, the device always answers to the same name. A small web server on the board lets you control the LED from your browser at http://bluegrays-esp.local/.

4.8(14)
23