All posts

ESP32-CAM object detection without training a model: the Arduino sketch

Most ESP32-CAM object detection tutorials start by training a model. This one asks a question in plain words instead: the full Arduino sketch, its settings, and when training is the better choice.

By Oussama Messai Published 2 December 2026 13 min read Lire cet article en français
A parcel left on the doormat of a house porch, seen from above the door

An Arduino reads a button, a thermometer, a distance sensor. Each of those gives it a number. What it has never had is a sensor for questions like “has the parcel arrived?” or “is the gate open?”, because the answer to those is not a number. It is something you see.

A camera board and an API that answers questions about pictures make that sensor. The board takes a picture, sends it with a question, and gets back a yes or a no that a sketch can use like any other input: if (flagged).

This post does it on a board small enough to hide above a door: an ESP32-CAM, programmed in C++ from the Arduino IDE.1

The usual route: train a model first

Search for ESP32-CAM object detection and most tutorials follow the same path. Collect pictures of each object (one widely read tutorial asks for at least 50 per object3), label them, train a small model on a training platform, export it as an Arduino library, and flash it. The model then runs on the board itself, which is a real advantage. It also recognises only the objects it was trained on, in conditions close to the training pictures, and every new object means going round the loop again.

This post takes the other route. The board does not recognise anything. It sends the picture with a question written in plain words, and a model on a server answers. There is nothing to collect, label or train, and changing what the board looks for means changing a sentence.

Neither route is better in every case. The last section says when training your own model is the right call.

Which board, and why not an Uno

The call to the API is an HTTPS request carrying a JPEG. That needs three things a classic Arduino Uno does not have: a camera, a network connection, and enough memory to hold a picture and do the encryption.

The ESP32-CAM has all three on one small board: a camera, Wi-Fi, and memory for an 800 by 600 JPEG. It is programmed with the same Arduino IDE and the same setup() and loop(), so everything else you know about Arduino still applies. If you already have an Uno project, keep it: let the ESP32-CAM do the seeing and raise one of its pins, and read that pin from the Uno like a button.

The example

A parcel on the doormat. The board sits above the door, looks down at the mat, and asks every five minutes “Is there a parcel on the doormat?”. While the answer is yes, an LED is lit. Swap the LED for a buzzer or a relay and it is a different project with the same sketch.

If you need to know where the objects are and not only whether they are there, save an agent of type detect with the classes to look for. The answer then carries one labelled point per object in result.regions, and flagged is true when at least one was found. The sketch below reads only flagged.

Three things to prepare

A saved agent. Write the question once in the console, save it as an agent, and put only its id in the sketch. You can then reword the question from your desk without climbing up to reflash the board. Each change is a new version, so a board can also be pinned to one.

A Run only key. The key is stored on the board, and anyone holding the board can read it out. A Run only key can run checks and nothing else, and you revoke it from the console if the board goes missing. While you build, use a test key: it is free and gives the same answer for the same picture.

The root certificate. Before it sends the key, the board must check that it is really talking to Camly. Get the root certificate with openssl s_client -showcerts -connect api.camly.ai:443 (it is the last certificate of the chain) and paste it into ROOT_CA. Do not turn the check off to save time: the key would then travel to whoever answers.

The sketch

Arduino IDE, board “AI Thinker ESP32-CAM”, library ArduinoJson 7.

// ESP32-CAM (AI-Thinker) + Camly: one picture every five minutes, checked by a saved agent.
// Arduino IDE, board "AI Thinker ESP32-CAM", library ArduinoJson 7.
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <ArduinoJson.h>
#include "esp_camera.h"

const char* WIFI_SSID = "your-network";
const char* WIFI_PASS = "your-password";
const char* API_HOST  = "api.camly.ai";
const char* API_KEY   = "cmly_sk_test_...";   // a Run only key; a test key while you build
const char* AGENT_ID  = "agt_...";            // the saved agent this camera runs
const char* DEVICE_ID = "doormat";            // names this camera in the Idempotency-Key
const char* ROOT_CA   = R"(-----BEGIN CERTIFICATE-----
...the root certificate of api.camly.ai, see above...
-----END CERTIFICATE-----)";
const unsigned long EVERY_MS = 300UL * 1000;
const int LED_PIN = 4;                        // the board's white LED: lit while flagged

bool startCamera() {
  camera_config_t c = {};
  c.pin_pwdn = 32;  c.pin_reset = -1; c.pin_xclk = 0;
  c.pin_sccb_sda = 26; c.pin_sccb_scl = 27;
  c.pin_d7 = 35; c.pin_d6 = 34; c.pin_d5 = 39; c.pin_d4 = 36;
  c.pin_d3 = 21; c.pin_d2 = 19; c.pin_d1 = 18; c.pin_d0 = 5;
  c.pin_vsync = 25; c.pin_href = 23; c.pin_pclk = 22;
  c.xclk_freq_hz = 20000000;
  c.ledc_timer = LEDC_TIMER_0; c.ledc_channel = LEDC_CHANNEL_0;
  c.pixel_format = PIXFORMAT_JPEG;
  c.frame_size = FRAMESIZE_SVGA;              // 800 x 600 is plenty: larger sides are scaled to 1280
  c.jpeg_quality = 12;
  c.fb_count = 1;
  c.fb_location = CAMERA_FB_IN_PSRAM;
  c.grab_mode = CAMERA_GRAB_LATEST;
  return esp_camera_init(&c) == ESP_OK;
}

// Sends one picture. Returns the HTTP status (0 when the connection failed); sets flagged and,
// on a 429, retryAfter in seconds.
int sendFrame(uint32_t n, bool& flagged, int& retryAfter) {
  camera_fb_t* fb = esp_camera_fb_get();
  if (!fb) return 0;
  WiFiClientSecure tls;
  tls.setCACert(ROOT_CA);
  tls.setTimeout(60);
  if (!tls.connect(API_HOST, 443)) { esp_camera_fb_return(fb); return 0; }

  String boundary = "camly" + String(esp_random(), HEX);
  String head = "--" + boundary + "\r\n"
                "Content-Disposition: form-data; name=\"agent\"\r\n\r\n" + AGENT_ID + "\r\n"
                "--" + boundary + "\r\n"
                "Content-Disposition: form-data; name=\"image\"; filename=\"frame.jpg\"\r\n"
                "Content-Type: image/jpeg\r\n\r\n";
  String tail = "\r\n--" + boundary + "--\r\n";

  // HTTP/1.0: the answer comes back in one piece, never chunked.
  tls.printf("POST /v1/runs HTTP/1.0\r\nHost: %s\r\n", API_HOST);
  tls.printf("Authorization: Bearer %s\r\n", API_KEY);
  tls.printf("Idempotency-Key: %s-%lu\r\n", DEVICE_ID, (unsigned long)n);
  tls.printf("Content-Type: multipart/form-data; boundary=%s\r\n", boundary.c_str());
  tls.printf("Content-Length: %u\r\n\r\n", (unsigned)(head.length() + fb->len + tail.length()));
  tls.print(head);
  for (size_t i = 0; i < fb->len; i += 1024) tls.write(fb->buf + i, std::min<size_t>(1024, fb->len - i));
  tls.print(tail);
  esp_camera_fb_return(fb);

  int status = tls.readStringUntil('\n').substring(9, 12).toInt();
  while (tls.connected() || tls.available()) {
    String line = tls.readStringUntil('\n');
    if (line.startsWith("Retry-After:")) retryAfter = line.substring(12).toInt();
    if (line == "\r") break;                  // end of the headers
  }
  String body = tls.readString();
  tls.stop();

  JsonDocument run;
  if (status == 200 && !deserializeJson(run, body)) flagged = run["result"]["flagged"] | false;
  else Serial.printf("Camly answered %d: %s\n", status, body.c_str());
  return status;
}

void setup() {
  Serial.begin(115200);
  pinMode(LED_PIN, OUTPUT);
  WiFi.begin(WIFI_SSID, WIFI_PASS);
  while (WiFi.status() != WL_CONNECTED) delay(500);
  if (!startCamera()) { Serial.println("Camera failed to start"); ESP.restart(); }
}

void loop() {
  static uint32_t n = 0;
  n++;                                        // one number per picture, kept across retries
  for (int attempt = 0; attempt < 3; attempt++) {
    bool flagged = false; int retryAfter = 0;
    int status = sendFrame(n, flagged, retryAfter);
    if (status == 200) { digitalWrite(LED_PIN, flagged ? HIGH : LOW); break; }
    if (status == 429) { delay(1000UL * (retryAfter > 0 ? retryAfter : 10)); continue; }
    if (status == 0 || status >= 500) { delay(2000UL << attempt); continue; }   // never charged: retry
    Serial.println("Fix the key, the balance or the agent before sending more.");
    while (true) delay(60000);                // 401, 402, 403, 404, 422: retrying will not help
  }
  delay(EVERY_MS);
}

The sketch comes from the API’s own documentation, with the pace set to five minutes for this example. As with any sketch copied from a page, compile it, read the serial monitor, and adapt the pins if your board is not the AI-Thinker model.

What the sketch is careful about

It sends the JPEG as it is. The picture goes as multipart, the raw bytes written to the connection a kilobyte at a time. Encoding it in base64 first would need a third more memory, and memory is what this board is short of.

It numbers its pictures. Each picture gets a number, and the Idempotency-Key header carries the board’s name and that number. If the Wi-Fi drops after the picture left but before the answer arrived, the retry carries the same key: the API returns the first answer and charges once.

It sorts errors by what they need.

The board getsIt meansThe sketch
200An answerSets the LED from flagged
429Too many checks this minuteWaits the seconds in Retry-After, sends again
502, or no connectionNothing was chargedRetries with a growing pause, same key
401, 402, 403, 404, 422The key, the balance or the agent needs fixingStops sending

The last line is what keeps a broken board from repeating a refusal every five minutes for a month.

It speaks HTTP/1.0. The answer then comes back in one piece, which keeps the reading code to a few lines.

Three settings that decide whether it works

The picture size. FRAMESIZE_SVGA is 800 by 600. The API scales anything larger down to 1280 pixels on its longest side, so a bigger picture buys little and costs memory and upload time. If what you watch is small in the frame, move the board closer before raising the size.

The pace. EVERY_MS is the time between pictures. Every picture is one check, €0.005 at the time of writing, so the pace is the cost.1

EveryChecks a dayPer dayPer 30 days
5 minutes288€1.44€43.20
15 minutes96€0.48€14.40
Hour24€0.12€3.60

A parcel does not need a verdict every five minutes through the night: a sketch that only checks during delivery hours costs a fraction of the first line. And set a budget on the key in the console, so that a board stuck in a loop stops at an amount you chose; the reasons are in what it costs, and how to keep it that way.

The light. This is a small sensor behind a small lens. It needs light: at dusk the picture gets noisy and there is less in it to judge. The board’s own white LED is on pin 4, the pin this sketch uses as its signal, so if you want it as a flash, move the signal to another pin.

Try the question before the board

The slowest way to tune a question is to reflash a board each time. Take a few pictures with the board, or with a phone held where the board will be, and send them from your computer:

curl https://api.camly.ai/v1/runs \
  -H "Authorization: Bearer $CAMLY_API_KEY" \
  -F agent=agt_... \
  -F [email protected]

Read result.description as well as result.flagged. When the answers are right on a mat with a parcel, an empty mat and a mat with a pair of shoes on it, the question is ready, and only then is it worth mounting the board.

When training your own model is the better choice

Asking a server has costs that a model on the board does not have, and it is better to know them before you build.

A model trained and run on the boardA question sent to the API
Before the first resultPictures to collect and label, a model to trainA sentence to write
A new object or a new questionTrain againChange the sentence
Needs a networkNoYes, Wi-Fi with internet access
Time per answerShort, everything happens on the boardLonger: an upload, then an answer from a server
Running costNoneOne check per picture
The picture leaves the boardNoYes, it is checked and not kept

Train your own model when the board has no network, when you need many answers a second, when the pictures must not leave the device, or when the running cost has to be zero. Ask a question when the thing to see is hard to describe as a class (“is the bin overflowing?”, “is the gate open?”), when it changes often, or when you want a result this afternoon.

When a bigger board is the better choice

The ESP32-CAM is the right size for one question and one output. If you want to keep pictures, run two questions, or drive something with more logic than an LED, a board running Linux is easier: the same call is a few lines of Python. Three worked examples are in give a Raspberry Pi eyes, a Raspberry Pi that waters the seedlings when they wilt and a Raspberry Pi that stops a failed 3D print in the night.

And if the camera is a real network camera rather than a board, it may need no code at all: many can send their pictures by themselves, as described in no box, no code.

Sources

  1. Camly API, all guides as plain text: Send from a device, Saved agents, Retries, Keys, Limits and prices. platform.camly.ai
  2. Camly API contract (OpenAPI). api.camly.ai
  3. CircuitDigest, “Object Detection using ESP32-CAM and Edge Impulse”, July 2024. circuitdigest.com