Build Project

ESP32-CAM

ESP32-CAM QR Scanner: Quirc 1.2 Serial Decoding

Decode QR candidates locally with a defined AI-Thinker OV2640/PSRAM setup, Quirc 1.2 source files, checked grayscale buffers and length-bounded Serial output.

IntermediateAges 12+Setup time variesParts cost variesLocal camera bench — unverified hardware
QR-to-Serial decoding logical overview; not a photograph, physical wiring layout or recorded result
Jump to a section

What You Will Build

An offline QR-to-Serial demonstration on an identified classic AI-Thinker ESP32-CAM/OV2640 with working PSRAM. Captured grayscale frames pass through Quirc v1.2; only successful decode results print length-bounded escaped bytes. It does not open URLs, stream images, log to SD/MQTT or operate a lock. The existing illustration is conceptual, not a photograph or supplied decoded result.

Before You Start

Review baseline: Arduino-ESP32 3.3.2, its bundled esp_camera driver and classic AI-Thinker board profile. This is not a latest-release claim and does not establish compatibility with an ESP32-S3 camera board. Each camera_config_t is zero-initialized, has the complete AI-Thinker map and explicit frame-buffer settings. No separately installed camera library should override the bundled driver.

Parts

  • Documented AI-Thinker classic ESP32-CAM with OV2640Original AI-Thinker pin map, not ESP32-S3, ESP-EYE or an unidentified clone. Check board markings, schematic and camera label. No microSD card or flash LED used.
  • USB–UART adapter with verified 3.3 V TTL signalsCheck actual TX high level and VCCIO circuit before connection. A 3.3/5 V output jumper does not universally select UART logic. Use TX, RX and GND only; adapter power outputs remain disconnected.
  • Regulated 5 V / 2 A current-capable external supply and short leadsA planning allowance, not measured demand. Connect only to the documented board 5V input and GND; onboard regulation supplies the chip. Verify actual module input/regulator. Never put 5 V on 3V3 or UART/GPIO.
  • USB data cable, removable IO0 jumper and accessible RST buttonDisconnect power before changing wiring or the camera ribbon; avoid driving an unpowered board through UART.

Wiring

The OV2640 bus is already on the board. External wiring is only separate 5 V board power, common ground and 3.3 V UART. Adapter power outputs stay disconnected. Follow the manual IO0/RST sequence below.

Logical AI-Thinker ESP32-CAM programming and power map: separate 5 V board supply, verified 3.3 V UART crossed TX/RX, common ground, IO0 strap for upload reset only. Not physical header order.

Open wiring diagram full size

  1. 1

    Unplug USB and switch external power off before wiring. Identify the exact AI-Thinker/OV2640 board and the adapter signal voltage; stop if either is unknown.

  2. 2

    Connect adapter TX (3.3 V TTL) → U0R/GPIO3, adapter RX ← U0T/GPIO1, and GND ↔ GND. Leave adapter 5V, 3V3, DTR and RTS unconnected; this procedure uses manual reset.

  3. 3

    Connect external regulated 5 V positive only to the documented 5V input, and negative to board GND/common adapter ground. Never join two supply positive outputs. Check the actual board regulator and connector labels.

  4. 4

    Select Espressif board package 3.3.2 and AI Thinker ESP32-CAM in Arduino IDE. Verify the PSRAM setting/profile. Use the board-compatible partition menu; this sketch does not implement OTA. Open the adapter port.

  5. 5

    With all power off fit IO0→GND. Power the board and adapter, press/release the onboard RST button to sample GPIO0 LOW, then upload. Manual GPIO0 wiring alone does not reset the chip.

  6. 6

    After upload, power off both sources, remove IO0→GND, restore power and press/release RST for normal boot. GPIO0 now supplies camera XCLK; leaving it grounded prevents operation. Open Serial at 115200.

  7. 7

    Keep UART and board powered together while connected; disconnect both before altering signals/ribbon. Do not use GPIO16/17 (PSRAM), SD pins or GPIO4 flash LED for this example.

Wiring Reference

SignalESP32 PinDirectionNotes
Programmer TX / RXU0R GPIO3 / U0T GPIO1UART input / outputCross TX→RX; 3.3 V TTL only. Not RS-232 or 5 V UART.
External regulated supply5V / GNDBoard powerBoard regulator input, not chip/GPIO voltage. Adapter positive outputs NC.
Upload strap / camera clockGPIO0 → GND for reset into upload onlyBoot strap, then XCLK outputRemove strap with power off and reset to run.
OV2640 D0…D75, 18, 19, 21, 36, 39, 34, 35Camera data inputOnboard ribbon/internal wiring; do not externally rewire.
OV2640 XCLK/PCLK/VSYNC/HREF0 / 22 / 25 / 23Clock output / timing inputsAI-Thinker only, not WROVER-KIT or S3 map.
OV2640 SCCB SDA/SCL26 / 27Configuration busModern pin_sccb_sda/pin_sccb_scl API names.
Camera PWDN / RESET32 / -1Power-down / no dedicated sensor resetBoard RST resets the ESP32; camera reset=-1 is not the upload reset button.

Libraries and Setup

  • Espressif Arduino-ESP32 board package 3.3.2Install the exact review baseline; esp_camera is bundled. Use AI Thinker ESP32-CAM and its PSRAM setting.
  • Daniel Beer Quirc v1.2Use exactly the six upstream library files described below; no ambiguous zbar/Arduino-wrapper dependency.

Configure the Example

Review baseline: Arduino-ESP32 3.3.2, its bundled esp_camera driver and classic AI-Thinker board profile. This is not a latest-release claim and does not establish compatibility with an ESP32-S3 camera board. Each camera_config_t is zero-initialized, has the complete AI-Thinker map and explicit frame-buffer settings. No separately installed camera library should override the bundled driver.

Quirc setup: download upstream dlbeer/quirc tag v1.2 (not zbar or an unspecified Arduino wrapper). Save the .ino in its own sketch folder. Beside it put these six unmodified files from that tag’s lib/ directory: quirc.h, quirc_internal.h, quirc.c, identify.c, decode.c and version_db.c. Keep the .c extensions so Arduino compiles C separately; retain their license notices. Do not copy the desktop demo, JPEG/PNG/SDL tools or a second Quirc copy. Save/reopen the sketch folder so all source tabs/files are present. This source integration has been API-reviewed, not compiled in this environment.

Version-label caveat: upstream quirc.c at tag v1.2 still returns the string 1.0 from quirc_version(). The Serial label is not a reliable release check; identify the six files by the pinned v1.2 tag, not that string.

Code

Install the libraries above and match the configuration and wiring before uploading.

esp32-cam-qr-scanner.ino
// AI-Thinker classic ESP32-CAM + OV2640 only; Arduino-ESP32 3.3.2.
// The board takes regulated 5 V at 5V; UART signals must be 3.3 V.
#include <Arduino.h>
#include "esp_camera.h"

bool initCamera(bool grayscale) {
  if (grayscale && !psramFound()) {
    Serial.println("Grayscale example requires enabled PSRAM; stopped");
    return false;
  }
  camera_config_t c = {};
  c.ledc_channel = LEDC_CHANNEL_0;
  c.ledc_timer = LEDC_TIMER_0;
  c.pin_d0 = 5; c.pin_d1 = 18; c.pin_d2 = 19; c.pin_d3 = 21;
  c.pin_d4 = 36; c.pin_d5 = 39; c.pin_d6 = 34; c.pin_d7 = 35;
  c.pin_xclk = 0; c.pin_pclk = 22; c.pin_vsync = 25; c.pin_href = 23;
  c.pin_sccb_sda = 26; c.pin_sccb_scl = 27;
  c.pin_pwdn = 32; c.pin_reset = -1;
  c.xclk_freq_hz = 20000000;
  c.pixel_format = grayscale ? PIXFORMAT_GRAYSCALE : PIXFORMAT_JPEG;
  c.frame_size = FRAMESIZE_QVGA; // 320 x 240; not a promised frame rate.
  c.jpeg_quality = 12; // Used only for JPEG.
  c.fb_count = 1;
  c.grab_mode = CAMERA_GRAB_WHEN_EMPTY;
  c.fb_location = psramFound() ? CAMERA_FB_IN_PSRAM : CAMERA_FB_IN_DRAM;
  esp_err_t err = esp_camera_init(&c);
  if (err != ESP_OK) {
    Serial.printf("Camera init failed: 0x%x; stopped\n", unsigned(err));
    return false;
  }
  sensor_t *sensor = esp_camera_sensor_get();
  if (!sensor || sensor->id.PID != OV2640_PID) {
    Serial.println("This example requires OV2640; stopped");
    esp_camera_deinit();
    return false;
  }
  Serial.printf("Camera initialized; PSRAM %s\n", psramFound() ? "found" : "not found");
  return true;
}

#include "quirc.h" // Upstream dlbeer/quirc v1.2; see exact source-file setup.
#include <cstring>
struct quirc *decoder = nullptr;
static struct quirc_code qrCode;
static struct quirc_data qrData; // Avoid putting these large objects on loop's stack.
bool ready = false;
uint32_t lastScan = 0;

void setup() {
  Serial.begin(115200);
  if (!initCamera(true)) return;
  decoder = quirc_new();
  if (!decoder || quirc_resize(decoder, 320, 240) != 0) {
    Serial.println("Quirc allocation failed; no scans will run");
    if (decoder) quirc_destroy(decoder);
    decoder = nullptr;
    esp_camera_deinit();
    return;
  }
  Serial.printf("Quirc %s; show a non-sensitive printed test QR\n", quirc_version());
  ready = true;
}
void loop() {
  if (!ready) { delay(100); return; }
  if (uint32_t(millis() - lastScan) < 500) { delay(1); return; }
  lastScan = millis();
  camera_fb_t *fb = esp_camera_fb_get();
  if (!fb) { Serial.println("Frame unavailable; retrying later"); return; }
  int w = 0, h = 0;
  uint8_t *pixels = quirc_begin(decoder, &w, &h);
  if (!pixels || fb->format != PIXFORMAT_GRAYSCALE ||
      w != 320 || h != 240 || fb->width != size_t(w) || fb->height != size_t(h) ||
      fb->len != size_t(w) * size_t(h)) {
    Serial.println("Unexpected frame/buffer layout; scan skipped");
    esp_camera_fb_return(fb);
    return;
  }
  memcpy(pixels, fb->buf, size_t(w) * size_t(h));
  esp_camera_fb_return(fb); // Do not retain the driver's frame during decoding.
  quirc_end(decoder);
  int count = quirc_count(decoder);
  if (count == 0) Serial.println("No QR candidate in this frame");
  for (int i = 0; i < count; ++i) {
    quirc_extract(decoder, i, &qrCode);
    quirc_decode_error_t err = quirc_decode(&qrCode, &qrData);
    if (err != QUIRC_SUCCESS) {
      Serial.printf("Candidate decode failed: %s\n", quirc_strerror(err));
      continue;
    }
    if (qrData.payload_len < 0 || qrData.payload_len > QUIRC_MAX_PAYLOAD) {
      Serial.println("Unexpected payload length; ignored"); continue;
    }
    Serial.printf("Decoded %d bytes, ECI %lu: ", qrData.payload_len, (unsigned long)qrData.eci);
    // Print length-bounded bytes, not a presumed UTF-8 or zero-terminated string.
    for (int j = 0; j < qrData.payload_len; ++j) {
      uint8_t b = qrData.payload[j];
      if (b >= 32 && b <= 126 && b != '\\') Serial.write(b);
      else Serial.printf("\\x%02X", unsigned(b));
    }
    Serial.println(); // No URL opening, relay, lock, web UI, SD or MQTT action.
  }
}

How the Code Works

Initialization failure leaves scanning disabled. quirc_new/resize must succeed. Each frame must be exactly 320×240 one-byte grayscale, with matching Quirc dimensions and length, before memcpy. Return the camera frame before Quirc detection/decoding. Candidate count is not a decode-success count. Large code/data objects are static; failed decode attempts print an error. A successful result prints payload_len bytes with non-printable bytes escaped, never as an assumed zero-terminated UTF-8 string. The 500 ms scheduling interval is not a measured decoding rate; a slow decode extends it.

Expected Output

At 115200 baud, initialization should report camera/PSRAM and Quirc version. A readable non-sensitive printed code may yield a decoded byte count and escaped payload. Otherwise expect no candidate, decode error or capture failure messages. Compare the exact bytes against your known test content. No sample payload or decoded success is supplied as a recorded result.

Troubleshooting

  • Upload waits for connection Power off and verify crossed 3.3 V UART, common ground and port. Fit IO0→GND, power up and press RST before retrying upload. Do not infer UART voltage from a supply jumper.
  • Bootloader messages repeat after upload Power off, remove the IO0 jumper and restart with RST. GPIO0 must be available for camera XCLK in run mode.
  • Brownout or camera init error Record the printed error code. Disconnect power before checking board identity, camera orientation/ribbon latch, supply/regulator and short return leads. A higher current label alone does not diagnose the fault; do not disable brownout protection.
  • Unexpected sensor or missing PSRAM Use only the identified OV2640/AI-Thinker arrangement. Check board profile and PSRAM setting. The QR example stops without PSRAM; the QVGA JPEG checks use explicit one-buffer DRAM fallback. Do not substitute another camera map blindly.
  • quirc.h missing or undefined quirc symbols Verify all six v1.2 files beside the .ino, .c file extensions and no duplicate wrapper library. A header alone is not the implementation.
  • No candidate or repeated decode errors Use a simple large non-sensitive printed QR with quiet border, even light, stable camera and correct focus. Glare, blur, orientation, code density and memory can matter. Error correction is not a blanket guarantee of decoding 30% arbitrary image damage.
  • Quirc allocation fails Stop and inspect free heap, PSRAM configuration and exact package. PSRAM framebuffer availability does not guarantee every Quirc allocation. Do not ignore null/resize failures or force a decode.

Checks to Perform on Your Build

  • Documentation/API review only: no compilation or camera hardware operation recorded for this sketch.
  • Check exact board/sensor, UART signal level, regulator input and supply wiring with power off.
  • Record upload, boot, initialization and actual output separately. Upload completion alone is not camera-function evidence.

Practical Design Notes

The manufacturer V1.0 board specification lists a 5 V supply and external PSRAM; the ESP32 and UART remain in the 3.3 V signal domain. This does not establish the regulator or pinout of an unmarked clone. JPEG QVGA (320×240), one buffer, can use the driver's low-resolution DRAM path when PSRAM is unavailable. Grayscale QR capture explicitly requires PSRAM here. More buffers/resolution are not free upgrades: upstream recommends multiple frame buffers only with JPEG. No frame rate or memory availability is guaranteed.

Upgrade Ideas

  • SD, MQTT, validation and duplicate filtering require separate complete designs; the old incomplete advanced snippets are not supported examples.

FAQs

Does a captured frame prove a QR code was decoded?

No. Only QUIRC_SUCCESS identifies a successful library decode. Compare returned bytes with known content; an IP address, image or upload log is different evidence.

Can this unlock a door or trust scanned URLs?

No. Decoded bytes are untrusted, may repeat and may not be text. No identity, replay prevention, access-control protocol or actuator is implemented.

Review, Testing, and References

Author: Abdul Mubeen and the ESP32 Engine editorial team. Last updated: 2026-11-17. Reviewed: wiring logic, Arduino code structure, beginner safety, and learning sequence.

Educational level: Intermediate. Estimated completion time: Setup time varies. This project is for learning and prototyping; production or unattended hardware needs additional engineering review.