VoltBench

How to connect a camera to an ESP32 (OV7670 wiring, code and live simulator)

An OV7670 camera module connects to an ESP32 with 18 wires: power, reset and power-down, the two control-bus wires (SDA and SCL), a clock output (XCLK), three sync signals (VSYNC, HREF, PCLK) and eight data lines (D0 to D7). The ESP32 sets the sensor up over I2C, reads the pixels itself and serves each picture on a web page. Below are the exact pins, the code, and a circuit you can run in your browser before you touch a wire.

Run it in your browser (free simulator)

Press ▶ Simulate in the box above. Nothing to install and no account needed. Open it in the workbench to change it (free account).

  1. Press Simulate

    The circuit above is the wiring from the table: an ESP32 DevKit and an OV7670 with 18 wires. Press ▶ Simulate. The board joins the virtual Wi-Fi and starts its web server.

  2. Open the Browser tab

    Switch to the Browser tab beside the circuit. It is a phone on the same Wi-Fi as the board. The board's address (like http://192.168.x.x/) is printed in the serial console, and the board appears as a button at the top of the Browser tab: click it to open the page.

  3. Press Take photo

    The board reads one picture from the camera and the page shows it. In this demo the camera shows a test pattern (colour bars), so it works without a webcam. In the full workbench you can switch the camera part to your own webcam.

  4. Break the wiring

    Open the circuit in the workbench and remove the XCLK wire and run it again: the camera cannot start. This is what a missing wire looks like, without risking a real board.

What you need

  • An ESP32 DevKit board (the usual 30 or 38 pin board with a USB port) and its USB cable
  • An OV7670 camera module, the bare 18-pin one (without the FIFO chip)
  • 18 female-to-female jumper wires, or a breadboard and jumpers
  • A 2.4 GHz Wi-Fi network (the ESP32 does not join 5 GHz)
  • Arduino IDE with the ESP32 board package installed (for the real board)

Careful: The OV7670 is a 3.3 V part. Power it from the ESP32 3V3 pin. Connecting 5 V (VIN or VBUS) to its power pin can destroy the sensor.

ESP32 and OV7670 wiring: pin by pin

Connect each OV7670 pin to the ESP32 pin on the same row. The data and sync pins can be moved to other GPIOs, but then the code has to change too; keep this table and the code works as it is.

ESP32 and OV7670 wiring: pin by pin
OV7670 pinESP32 pinWhat it does
3V33V3Power, 3.3 V
GNDGNDGround
RESET3V3Held high: the sensor is not in reset
PWDNGNDHeld low: the sensor is not powered down
MCLK (XCLK)GPIO21Clock for the sensor, 20 MHz from the ESP32
SDA (SIOD)GPIO26Control bus data (I2C, address 0x21)
SCL (SIOC)GPIO27Control bus clock
VS (VSYNC)GPIO25A new picture starts
HS (HREF)GPIO23A line of the picture is valid
PCLKGPIO22One pixel byte is ready on D0 to D7
D0GPIO4Pixel data bit 0
D1GPIO5Pixel data bit 1
D2GPIO18Pixel data bit 2
D3GPIO19Pixel data bit 3
D4GPIO36 (VP)Pixel data bit 4 (input-only pin, fine for data)
D5GPIO39 (VN)Pixel data bit 5 (input-only pin, fine for data)
D6GPIO34Pixel data bit 6 (input-only pin, fine for data)
D7GPIO35Pixel data bit 7 (input-only pin, fine for data)

Do not leave XCLK out: without a clock the sensor never answers on the control bus, and the code reports that the camera did not start. These pins are for an ESP32 DevKit with an OV7670. The ESP32-CAM board has a different camera (OV2640) soldered on with its own fixed pins and needs a different sketch.

How the code works

The sketch does three jobs. First it joins your Wi-Fi and starts a small web server on port 80. Second, when the page asks for a photo, it starts the 20 MHz clock on XCLK, lets the sensor settle its exposure for a second, then reads the picture pin by pin: it waits for VSYNC, then for each HREF line it reads D0 to D7 every time PCLK rises. Third, it sends the picture to the page, which draws it on a canvas.

The sensor is set up with the standard register list for VGA RGB565 output over the control bus (the Wire library, address 0x21). The pixel clock is slowed to about 1.25 MHz so the ESP32 can read every byte by polling, and the picture is averaged down to 240 by 180 pixels. The price of this simple method is speed: one picture takes a few seconds, so this is a photo page, not live video. For video use an ESP32-CAM board, which has a camera interface built for it.

The clock on XCLK is also a source of radio noise next to the Wi-Fi antenna, so the code only runs it while the sensor is being set up or a picture is taken.

Put it on the real ESP32

  1. Install the ESP32 board package

    In Arduino IDE open Boards Manager, install "esp32 by Espressif Systems", then choose ESP32 Dev Module as the board.

  2. Wire it exactly as in the table

    Check each of the 18 wires once more with the board unplugged. Most "it does not work" reports are one loose or swapped data wire.

  3. Set your Wi-Fi and upload

    Copy the code from the box below into a new sketch, change SSID and PASSWORD to your network, choose the port and press Upload.

  4. Read the address and open it

    Open the Serial Monitor at 115200 baud. When the board has joined, it prints its address. Open that address in a browser on the same network and press Take photo.

The code (Arduino C++)

This is the Arduino code for the real ESP32 (it needs the ESP32 board package). The simulator runs it too.

Show the code (394 lines)
// ESP32 + OV7670 (real board): a "Take photo" button on a web page. Open the address it prints in a browser on the
// same Wi-Fi and press the button: every press takes one picture and the page shows it.
#include <WiFi.h>
#include <WebServer.h>

const char* SSID = "HomeWiFi";
const char* PASSWORD = "12345678";
const int PORT = 80;
const int FLASH = 2;  // the board's own LED lights while a picture is taken

WebServer server(PORT);
int shots = 0;
bool cameraOk = false;  // the web server runs even when the camera does not start, so you can see why

const char PAGE[] PROGMEM = R"rawliteral(<!doctype html>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
  body { font-family: system-ui, sans-serif; text-align: center; margin: 20px; background: #111; color: #eee; }
  button { font-size: 22px; padding: 14px 28px; border: 0; border-radius: 10px; color: #fff; background: #2563eb; }
  button:disabled { background: #475569; }
  #big { display: block; margin: 16px auto; width: 320px; max-width: 100%; border-radius: 8px; background: #000; min-height: 60px; }
  #thumbs img { width: 96px; margin: 4px; border-radius: 4px; cursor: pointer; }
</style>
<h2>ESP32 camera</h2>
<button id="btn">Take photo</button>
<img id="big" alt="">
<p id="info">No photo yet.</p>
<div id="thumbs"></div>
<script>
  // the board sends the raw picture (RGB565, 2 bytes per pixel, size in the X-Width and X-Height headers): draw it here and make an image of it
  function draw(buf, w, h) {
    const c = document.createElement('canvas');
    c.width = w;
    c.height = h;
    const ctx = c.getContext('2d');
    const img = ctx.createImageData(w, h);
    for (let i = 0; i < w * h; i++) {
      const v = (buf[2 * i + 1] << 8) | buf[2 * i];
      img.data[4 * i] = ((v >> 11) & 31) * 255 / 31;
      img.data[4 * i + 1] = ((v >> 5) & 63) * 255 / 63;
      img.data[4 * i + 2] = (v & 31) * 255 / 31;
      img.data[4 * i + 3] = 255;
    }
    ctx.putImageData(img, 0, 0);
    return c.toDataURL('image/png');
  }
  const btn = document.getElementById('btn');
  btn.onclick = async () => {
    btn.disabled = true;
    btn.textContent = 'Taking...';
    try {
      const r = await fetch('/photo');
      if (!r.ok) throw new Error(await r.text());
      const p = { n: r.headers.get('X-Shot'), width: +r.headers.get('X-Width'), height: +r.headers.get('X-Height'), brightness: r.headers.get('X-Brightness') };
      const src = draw(new Uint8Array(await r.arrayBuffer()), p.width, p.height);
      document.getElementById('big').src = src;
      document.getElementById('info').textContent = 'Photo #' + p.n + ' - ' + p.width + 'x' + p.height + ' - brightness ' + p.brightness;
      const t = document.createElement('img');
      t.src = src;
      t.onclick = () => (document.getElementById('big').src = src);
      document.getElementById('thumbs').prepend(t);
    } catch (e) {
      document.getElementById('info').textContent = 'Failed: ' + e;
    }
    btn.disabled = false;
    btn.textContent = 'Take photo';
  };
</script>)rawliteral";

// Wiring, OV7670 pin -> ESP32 pin (18 wires). Do not leave one out: without XCLK the sensor has no clock and never answers.
//   3V3 -> 3V3     GND -> GND     RESET -> 3V3     PWDN -> GND
//   XCLK (MCLK) -> GPIO21     SIOD (SDA) -> GPIO26     SIOC (SCL) -> GPIO27
//   VSYNC -> GPIO25     HREF -> GPIO23     PCLK -> GPIO22
//   D0 -> GPIO4   D1 -> GPIO5   D2 -> GPIO18   D3 -> GPIO19   D4 -> GPIO36 (VP)   D5 -> GPIO39 (VN)   D6 -> GPIO34   D7 -> GPIO35
//
// This driver does not use esp_camera: it sets the sensor up over I2C (Wire) and reads the pins itself, so it works with
// OV7670 modules the esp_camera driver cannot talk to. The sensor is slowed down (PCLK about 1.25 MHz) so the ESP32 can read
// every byte by polling; one picture takes a few seconds. The result is 240 x 180, RGB565, sent as raw bytes to the web page.
#include <Wire.h>
#include "soc/gpio_reg.h"
#include "esp_camera.h"

const int PIN_XCLK = 21, PIN_SDA = 26, PIN_SCL = 27;
const uint32_t M_PCLK = 1u << 22, M_HREF = 1u << 23, M_VSYNC = 1u << 25;  // GPIO22, 23, 25 in GPIO_IN_REG
const int PIXEL_PINS[] = {4, 5, 18, 19, 36, 39, 34, 35, 22, 23, 25};
const int PW = 240, PH = 180;  // the picture we keep: the sensor's 640 x 480 averaged down by 8/3 (each output pixel is the mean of 2-3 x 2-3 sensor pixels)
const uint8_t SLOW_CLKRC = 0x0F;  // read at XCLK / 16 (1.25 MHz pixel clock): the ESP32 can poll every byte at this speed
const int SLOW_DIV = 16;
const bool SWAP_BYTES = false;  // set to true if the colours look wrong (red and blue mixed up, green noise)
const int FRAME_BYTES = PW * PH * 2;
uint16_t* frame = nullptr;  // RGB565, allocated at start (86 KB is too much for static memory)
const int LINE_BYTES = 1400;
uint8_t lineBuf[LINE_BYTES];  // the bytes of the line being read
uint16_t accR[PW], accG[PW], accB[PW], accN[PW];  // sums of the sensor pixels that fall into each output pixel of the current output row
unsigned long lastTry = 0;  // millis() of the last attempt: do not hammer a camera that fails
String cameraWhy = "";      // what went wrong, for the page and the serial monitor

bool sccbWrite(uint8_t reg, uint8_t value) {
  Wire.beginTransmission(0x21);
  Wire.write(reg);
  Wire.write(value);
  return Wire.endTransmission() == 0;
}

uint8_t sccbRead(uint8_t reg) {
  Wire.beginTransmission(0x21);
  Wire.write(reg);
  Wire.endTransmission();
  Wire.requestFrom(0x21, 1);
  return Wire.available() ? Wire.read() : 0xFF;
}

// Register values of the OV7670 for VGA, RGB565 output (the widely used set from the Linux driver), then the clock changes.
struct Reg { uint8_t reg, value; };
const Reg OV7670_REGS[] = {
  {0x3A, 0x04}, {0x12, 0x04},                                              // TSLB, COM7: RGB output, VGA
  {0x17, 0x13}, {0x18, 0x01}, {0x32, 0xB6}, {0x19, 0x02}, {0x1A, 0x7A}, {0x03, 0x0A},  // window
  {0x0C, 0x00}, {0x3E, 0x00}, {0x70, 0x3A}, {0x71, 0x35}, {0x72, 0x11}, {0x73, 0xF0}, {0xA2, 0x02}, {0x15, 0x00},
  {0x7A, 0x20}, {0x7B, 0x10}, {0x7C, 0x1E}, {0x7D, 0x35}, {0x7E, 0x5A}, {0x7F, 0x69}, {0x80, 0x76}, {0x81, 0x80},  // gamma
  {0x82, 0x88}, {0x83, 0x8F}, {0x84, 0x96}, {0x85, 0xA3}, {0x86, 0xAF}, {0x87, 0xC4}, {0x88, 0xD7}, {0x89, 0xE8},
  {0x13, 0x88}, {0x00, 0x00}, {0x10, 0x00}, {0x0D, 0x40}, {0x14, 0x18}, {0x24, 0x95}, {0x25, 0x33}, {0x26, 0xE3},  // exposure
  {0x9F, 0x78}, {0xA0, 0x68}, {0xA1, 0x03}, {0xA6, 0xD8}, {0xA7, 0xD8}, {0xA8, 0xF0}, {0xA9, 0x90}, {0xAA, 0x94},
  {0x13, 0xE5}, {0x0E, 0x61}, {0x0F, 0x4B}, {0x16, 0x02}, {0x1E, 0x07}, {0x21, 0x02}, {0x22, 0x91}, {0x29, 0x07},
  {0x33, 0x0B}, {0x35, 0x0B}, {0x37, 0x1D}, {0x38, 0x71}, {0x39, 0x2A}, {0x3C, 0x78}, {0x4D, 0x40}, {0x4E, 0x20},
  {0x69, 0x00}, {0x74, 0x10}, {0x8D, 0x4F}, {0x8E, 0x00}, {0x8F, 0x00}, {0x90, 0x00}, {0x91, 0x00}, {0x96, 0x00},
  {0x9A, 0x00}, {0xB0, 0x84}, {0xB1, 0x0C}, {0xB2, 0x0E}, {0xB3, 0x82}, {0xB8, 0x0A},
  {0x43, 0x0A}, {0x44, 0xF0}, {0x45, 0x34}, {0x46, 0x58}, {0x47, 0x28}, {0x48, 0x3A}, {0x59, 0x88}, {0x5A, 0x88},  // white balance
  {0x5B, 0x44}, {0x5C, 0x67}, {0x5D, 0x49}, {0x5E, 0x0E}, {0x6C, 0x0A}, {0x6D, 0x55}, {0x6E, 0x11}, {0x6F, 0x9F},
  {0x6A, 0x40}, {0x01, 0x40}, {0x02, 0x60}, {0x13, 0xE7},
  {0x4F, 0xB3}, {0x50, 0xB3}, {0x51, 0x00}, {0x52, 0x3D}, {0x53, 0xA7}, {0x54, 0xE4}, {0x58, 0x9E},  // colour matrix
  {0x41, 0x08}, {0x3F, 0x00}, {0x75, 0x05}, {0x76, 0xE1}, {0x4C, 0x00}, {0x77, 0x01}, {0x3D, 0xC3}, {0x4B, 0x09},
  {0xC9, 0x60}, {0x56, 0x40}, {0x34, 0x11}, {0x3B, 0x12}, {0xA4, 0x88}, {0x97, 0x30}, {0x98, 0x20}, {0x99, 0x30},
  {0x9B, 0x29}, {0x9C, 0x03}, {0x9D, 0x4C}, {0x9E, 0x3F}, {0x78, 0x04},
  {0x04, 0x00}, {0x40, 0xD0}, {0x8C, 0x00}, {0x1E, 0x07},                  // COM15: RGB565 full range, no RGB444, mirror/flip off-ish
  {0x6B, 0x0A},                                                              // DBLV: PLL bypassed
  {0x11, 0x00},                                                              // CLKRC: full speed; takePhoto() slows the clock down for the frame it reads
};

// The 20 MHz clock on XCLK is a strong radio noise source next to the Wi-Fi antenna (ping went to seconds with it running), so
// it only runs while the sensor is being set up or a picture is taken, and the pin is held low the rest of the time.
void clockOn() {
  ledcAttach(PIN_XCLK, 20000000, 1);
  ledcWrite(PIN_XCLK, 1);
}

void clockOff() {
  ledcDetach(PIN_XCLK);
  pinMode(PIN_XCLK, OUTPUT);
  digitalWrite(PIN_XCLK, LOW);
}

bool startCamera() {
  lastTry = millis();
  if (!frame) frame = (uint16_t*)malloc(FRAME_BYTES);
  if (!frame) {
    cameraWhy = "not enough memory for the picture";
    return false;
  }
  clockOn();
  delay(300);                          // the sensor needs a moment with its clock before it talks
  Wire.end();
  Wire.begin(PIN_SDA, PIN_SCL, 50000);
  for (int pin : PIXEL_PINS) pinMode(pin, INPUT);

  uint8_t ver = sccbRead(0x0B);
  ver = sccbRead(0x0B);  // the first read after start can be stale
  Serial.printf("OV7670: PID=0x%02X VER=0x%02X MID=0x%02X%02X\n", sccbRead(0x0A), ver, sccbRead(0x1C), sccbRead(0x1D));
  if (ver != 0x73) {
    cameraWhy = "the sensor does not answer on the control bus: check XCLK, SIOD, SIOC, 3.3 V, RESET (to 3.3 V) and PWDN (to GND)";
    clockOff();
    return false;
  }
  sccbWrite(0x12, 0x80);  // COM7: reset all registers
  delay(100);
  for (const Reg& r : OV7670_REGS) {
    if (!sccbWrite(r.reg, r.value)) {
      cameraWhy = "the sensor stopped answering while it was being set up";
      clockOff();
      return false;
    }
  }
  delay(1000);  // full speed: exposure and white balance settle
  clockOff();
  cameraWhy = "";
  Serial.println("Camera ready (own driver, 240x180)");
  return true;
}

static inline uint8_t dataByte(uint32_t a, uint32_t b) {
  return ((a >> 4) & 1) | (((a >> 5) & 1) << 1) | (((a >> 18) & 1) << 2) | (((a >> 19) & 1) << 3) |
         (((b >> 4) & 1) << 4) | (((b >> 7) & 1) << 5) | (((b >> 2) & 1) << 6) | (((b >> 3) & 1) << 7);  // GPIO36, 39, 34, 35
}

// The mean of the sensor pixels collected for one output row becomes that row of frame[]; the sums start again.
void flushRow(int row) {
  if (row < 0 || row >= PH) return;
  for (int x = 0; x < PW; x++) {
    const uint16_t c = accN[x];
    if (c) {
      const uint16_t r = accR[x] / c, g = accG[x] / c, b = accB[x] / c;
      frame[row * PW + x] = (r << 11) | (g << 5) | b;
    }
    accR[x] = accG[x] = accB[x] = accN[x] = 0;
  }
}

// Reads one picture into frame[].  Returns false (and says why in cameraWhy) when the sensor does not send one.
bool captureFrame() {
  uint32_t t0 = millis();
  uint32_t a = 0, b = 0;
  // two frame starts: the exposure written just before only applies from the frame after the one that is running
  for (int skip = 0; skip < 2; skip++) {
    while (!((a = REG_READ(GPIO_IN_REG)) & M_VSYNC)) if (millis() - t0 > 12000) { cameraWhy = "no VSYNC from the sensor (is GPIO25 wired to VSYNC? is the clock running?)"; return false; }
    while ((a = REG_READ(GPIO_IN_REG)) & M_VSYNC) if (millis() - t0 > 12000) { cameraWhy = "VSYNC stays high"; return false; }
  }
  int y = 0, goodLines = 0, outRow = 0;
  uint32_t firstBytes = 0;
  memset(accR, 0, sizeof(accR)); memset(accG, 0, sizeof(accG)); memset(accB, 0, sizeof(accB)); memset(accN, 0, sizeof(accN));
  while (y < 480) {
    // the next line starts when HREF goes high; a new VSYNC means the picture is over
    while (true) {
      a = REG_READ(GPIO_IN_REG);
      if (a & M_HREF) break;
      if (a & M_VSYNC) goto finished;
      if (millis() - t0 > 20000) { cameraWhy = "no HREF from the sensor (is GPIO23 wired to HREF?)"; return false; }
    }
    {
      uint32_t n = 0;
      noInterrupts();  // a line is only about 1 ms: nothing may interrupt the polling
      while (true) {
        // every wait has a limit: with interrupts off, a sensor that stops sending would freeze the whole board (Wi-Fi included)
        uint32_t guard = 0;
        while (true) { a = REG_READ(GPIO_IN_REG); if (!(a & M_HREF) || ++guard > 200000) goto lineEnd; if (!(a & M_PCLK)) break; }   // PCLK low
        while (true) { a = REG_READ(GPIO_IN_REG); if (!(a & M_HREF) || ++guard > 400000) goto lineEnd; if (a & M_PCLK) break; }     // PCLK rises: data is valid
        if (n > 3000) goto lineEnd;  // a line is 1280 bytes: HREF stuck high
        if (n < LINE_BYTES) {
          b = REG_READ(GPIO_IN1_REG);
          lineBuf[n] = dataByte(a, b);
        }
        n++;
      }
lineEnd:
      interrupts();
      if (n > 1000) goodLines++;
      if (y == 0) firstBytes = n;
      if (n > 1000) {
        // The first bytes of a line pass before the program is ready to read: the line is complete at its end, so the bytes
        // that are missing are missing from the start. Put each byte where it belongs.
        const int missing = (n < 1280) ? (1280 - (int)n) : 0;
        const int oy = (y * 3) >> 3;  // the output row this sensor line belongs to
        if (oy != outRow) {
          flushRow(outRow);
          outRow = oy;
        }
        for (int px = 0; px < 640; px++) {
          const int i = px * 2 - missing;
          if (i < 0 || i + 1 >= (int)n || i + 1 >= LINE_BYTES) continue;
          const uint8_t hi = SWAP_BYTES ? lineBuf[i + 1] : lineBuf[i];
          const uint8_t lo = SWAP_BYTES ? lineBuf[i] : lineBuf[i + 1];
          const int ox = (px * 3) >> 3;
          accR[ox] += hi >> 3;
          accG[ox] += ((hi & 7) << 3) | (lo >> 5);
          accB[ox] += lo & 31;
          accN[ox]++;
        }
      }
      yield();  // Wi-Fi and the other tasks get their turn between lines
    }
    y++;
  }
finished:
  flushRow(outRow);
  Serial.printf("Picture: %d lines (%u bytes in the first), %lu ms\n", y, (unsigned)firstBytes, (unsigned long)(millis() - t0));
  if (goodLines < 100) { cameraWhy = "the sensor sent too few lines: is D0-D7 / PCLK wired right?"; return false; }
  return true;
}

String cameraProblem() {
  return String("The camera did not give a picture: ") + cameraWhy;
}

// Takes one picture into frame[] (240 x 180, RGB565) and gives back its average brightness (0-255). No JPEG: the encoder
// needs a 128 KB block of memory that an ESP32 running Wi-Fi does not have, so the raw picture is sent as it is.
bool takePhoto(int& brightness) {
  clockOn();
  // 1. Let the sensor's automatic exposure work out the light at full speed (about 25 frames a second).
  sccbWrite(0x13, 0xE7);
  sccbWrite(0x11, 0x00);
  delay(1000);
  const uint8_t gain = sccbRead(0x00), com1 = sccbRead(0x04), aec = sccbRead(0x07), aech = sccbRead(0x10);
  const uint8_t blue = sccbRead(0x01), red = sccbRead(0x02);  // white balance as the sensor found it
  uint32_t exposure = ((uint32_t)(aec & 0x3F) << 10) | ((uint32_t)aech << 2) | (com1 & 3);  // in lines
  // 2. Exposure is counted in lines, and at the slow clock a line lasts SLOW_DIV times longer: the same number of lines would
  //    be SLOW_DIV times too bright. Divide it, keep it fixed (automatic exposure off) and slow the clock for the frame we read.
  Serial.printf("Exposure at full speed: %u lines, gain 0x%02X\n", (unsigned)exposure, gain);
  exposure = exposure / SLOW_DIV;
  if (exposure < 1) exposure = 1;
  sccbWrite(0x13, 0xE0);  // automatic exposure, gain and white balance off: the picture we read keeps what was found at full speed
  sccbWrite(0x00, gain);
  sccbWrite(0x01, blue);
  sccbWrite(0x02, red);
  sccbWrite(0x04, (com1 & 0xFC) | (exposure & 3));
  sccbWrite(0x10, (exposure >> 2) & 0xFF);
  sccbWrite(0x07, (exposure >> 10) & 0x3F);
  sccbWrite(0x11, SLOW_CLKRC);
  const bool got = captureFrame();
  sccbWrite(0x13, 0xE7);  // all automatic again for the next picture
  sccbWrite(0x11, 0x00);
  clockOff();
  if (!got) return false;
  unsigned long sum = 0;
  int count = 0;
  for (int i = 0; i < PW * PH; i += 7) {
    const uint16_t p = frame[i];
    sum += ((((p >> 11) << 3) * 30) + ((((p >> 5) & 0x3F) << 2) * 59) + ((p & 0x1F) << 3) * 11) / 100;
    count++;
  }
  brightness = sum / count;
  return true;
}

void handleRoot() {
  server.send(200, "text/html", PAGE);
}


// The picture as raw bytes (RGB565, 2 bytes per pixel, little endian), about 38 KB; the web page draws it on a canvas.
void sendFrame(int shot, int brightness) {
  server.sendHeader("X-Shot", String(shot));
  server.sendHeader("X-Width", String(PW));
  server.sendHeader("X-Height", String(PH));
  server.sendHeader("X-Brightness", String(brightness));
  server.send_P(200, "application/octet-stream", (PGM_P)frame, FRAME_BYTES);
}

// the button calls this: one picture, as raw bytes
void handlePhoto() {
  if (!cameraOk && millis() - lastTry > 5000) cameraOk = startCamera();  // wiring fixed since the boot? try again
  if (!cameraOk) {
    server.send(503, "text/plain", cameraProblem());
    return;
  }
  digitalWrite(FLASH, HIGH);
  int brightness = 0;
  const bool ok = takePhoto(brightness);
  digitalWrite(FLASH, LOW);
  if (!ok) {
    Serial.println(cameraProblem());
    server.send(500, "text/plain", cameraProblem());
    return;
  }
  shots++;
  Serial.printf("Photo #%d taken, brightness %d\n", shots, brightness);
  sendFrame(shots, brightness);
}

void handleNotFound() {
  server.send(404, "text/plain", "Not found: " + server.uri());
}

void connectWiFi() {
  Serial.print("Connecting to ");
  Serial.println(SSID);
  WiFi.begin(SSID, PASSWORD);
  while (WiFi.status() != WL_CONNECTED) delay(250);
  WiFi.setSleep(false);  // no modem sleep: much lower ping and faster page loads
}

void setup() {
  Serial.begin(115200);
  pinMode(FLASH, OUTPUT);
  connectWiFi();
  cameraOk = startCamera();
  if (!cameraOk) Serial.println("Camera init failed: " + cameraWhy + " (the web page still works)");
  server.on("/", handleRoot);
  server.on("/photo", handlePhoto);
  server.onNotFound(handleNotFound);
  server.begin();
  Serial.print("Open http://");
  Serial.print(WiFi.localIP());
  Serial.println("/ in a browser and press the button");
}

unsigned long lastStatus = 0;

void loop() {
  server.handleClient();
  delay(2);
  if (millis() - lastStatus > 5000) {  // a heartbeat: Wi-Fi signal and free memory
    lastStatus = millis();
    Serial.printf("alive: Wi-Fi %d dBm, free memory %u bytes\n", WiFi.RSSI(), (unsigned)ESP.getFreeHeap());
  }
}

Troubleshooting

The page says the camera did not give a picture
The sensor did not answer on the control bus. Check 3V3 and GND first, then RESET (to 3V3), PWDN (to GND), SDA (GPIO26), SCL (GPIO27) and especially XCLK (GPIO21). The message on the page and in the Serial Monitor names the step that failed.
The picture has wrong colours, or green noise
The two bytes of each pixel are swapped. In the code set SWAP_BYTES to true. If the picture is shifted or torn, one of D0 to D7, HREF or PCLK is loose.
The picture is black or very dark
The sensor needs light and a second for its automatic exposure. Take a second photo in a lit room. A fully black picture with correct wiring usually means VSYNC or HREF is on the wrong pin.
The board resets when taking a photo
The supply sags. Use a good USB cable and port, or add a 100 µF capacitor between 3V3 and GND near the camera.
The ESP32 does not join the Wi-Fi
The ESP32 only uses 2.4 GHz networks. Check the name and password, and keep the board close to the router.

Frequently asked questions

Can I connect an ESP32 to a camera without extra chips?

Yes. The OV7670 module connects straight to the ESP32 GPIO pins with 18 wires, and the ESP32 reads the pixels itself, as this page shows. The ESP32 has no ready-made camera connector on a DevKit board, so the code does what a camera interface would do. It is slower than a board built for a camera, but it needs no additional hardware.

Does this work with the ESP32-CAM module?

No. The ESP32-CAM has an OV2640 camera on its own fixed pins and uses the esp_camera driver with a pin table for that board. This page is for a plain ESP32 DevKit and a separate OV7670 module. The ideas (3.3 V power, one wire per data bit, a web page for the picture) carry over, the pins and the code do not.

Which ESP32 pins does the OV7670 use?

In this wiring: GPIO21 for XCLK, GPIO26 and GPIO27 for the control bus, GPIO25 for VSYNC, GPIO23 for HREF, GPIO22 for PCLK and GPIO4, 5, 18, 19, 36, 39, 34, 35 for data bits D0 to D7. The full table is above.

Why does the OV7670 need a clock from the ESP32?

The sensor has no oscillator of its own. It needs an external clock on XCLK, 20 MHz here, produced by the ESP32 timer hardware. Without it the sensor does not run and does not answer on the control bus.

Can I test this without buying the camera?

Yes. The simulator on this page runs the same ESP32 code against a virtual OV7670 and a virtual Wi-Fi network, so you can check the wiring and the page before you buy or wire anything. It is free in the browser.

Is the simulation the same as the real board?

The wiring, the control-bus traffic and the web page are the same. Timing is not: the real board needs a few seconds per picture and depends on your light, cable and Wi-Fi. Use the simulator to get the wiring and the code right, then confirm on the hardware.

Embed this circuit on your own page

Copy this code into your blog, tutorial or course page. Visitors can run the circuit right there.

<iframe src="https://voltbench.click/embed/gallery/connect-camera-to-esp32" width="100%" height="560" style="border:1px solid #2a3140;border-radius:8px" loading="lazy" allowfullscreen title="How to connect a camera to an ESP32"></iframe>

Build your own version

Open this circuit in the VoltBench workbench, change the wiring or the code, and run it. When it works, flash a real board. Free to use.

Open in the workbench