ToolsWiFi

OTA: update ESP32 firmware over WiFi, no cable needed

Example code uses the Arduino core for ESP32 · needs a board with ≥ 4 MB flash

Once a device is in its enclosure, mounted on the ceiling or out in the garden, unplugging it to fix one line of code is a pain. OTA (Over-The-Air) lets you flash new firmware over WiFi. This article explains the mechanism underneath so you avoid the classic "bricked" situations, then shows three ways to implement it.

How does OTA work?

The ESP32's flash is divided into regions described by the partition table (stored at 0x8000). Safe OTA needs two app partitions used alternately: the running firmware lives in one, and the new image is written into the other. Only once it has been written and verified does the system switch over. If power is lost halfway, the old firmware is still intact and the device still boots.

boot32K0x1000nvs20K0x9000otadata8K0xE000app0 (ota_0)1280K0x10000app1 (ota_1)1280K0x150000spiffs1408K0x2900000x3F0000otadata points to the valid slotOTA writes here↑ Runningbootloader 0x1000 · partition table 0x8000
Figure 1: The default 4 MB flash layout of the ESP32 (Default 4MB with spiffs). Addresses are shown under each partition. This is an illustration; widths are not to scale.
PC / ServerESP32 (old app)Bootloader1. Send firmware.bin (over WiFi)2. Write chunk by chunk intothe idle partition (app1)3. Check size + MD5,set otadata → app14. Reboot5. Read otadata,pick app1✓ 6. New firmware runs from app1
Figure 2: The sequence of an OTA update. The old firmware stays intact in app0 until the new one is confirmed valid.
Requirements: (1) a board with ≥ 4 MB flash; (2) pick a Tools → Partition Scheme that supports OTA, for example "Default 4MB with spiffs" or "Minimal SPIFFS (1.9MB APP with OTA/190KB SPIFFS)". Schemes labelled "No OTA" or "Huge APP" have no room for a second image; (3) every program must contain its own OTA code. If you flash a sketch without OTA code you lose WiFi updates and have to use the cable again.

Method 1: ArduinoOTA (upload from the Arduino IDE or PlatformIO)

This is the simplest option during development. The ESP32 advertises itself via mDNS and the Arduino IDE lists it under Tools → Port → Network ports.

#include <WiFi.h>
#include <ArduinoOTA.h>

const char* WIFI_SSID = "ten_wifi";
const char* WIFI_PASS = "mat_khau_wifi";
const char* OTA_HOST  = "esp32diy-ota";            // name shown in the Arduino IDE / mDNS
const char* OTA_PASS  = "doi_mat_khau_nay";

const int LED = 2;
uint32_t lastBlink = 0;

void setup() {
  Serial.begin(115200);
  pinMode(LED, OUTPUT);

  WiFi.mode(WIFI_STA);
  WiFi.begin(WIFI_SSID, WIFI_PASS);
  while (WiFi.status() != WL_CONNECTED) delay(300);
  Serial.println(WiFi.localIP());

  ArduinoOTA.setHostname(OTA_HOST);
  ArduinoOTA.setPassword(OTA_PASS);
  ArduinoOTA.onStart([]() {
    // Put the device in a safe state: switch off relays, motors... before receiving firmware
    Serial.println(ArduinoOTA.getCommand() == U_FLASH ? "OTA: firmware" : "OTA: filesystem");
  });
  ArduinoOTA.onProgress([](unsigned int done, unsigned int total) {
    Serial.printf("OTA %u%%\r", done * 100 / total);
  });
  ArduinoOTA.onEnd([]() { Serial.println("\nOTA xong, khoi dong lai"); });
  ArduinoOTA.onError([](ota_error_t e) { Serial.printf("OTA error %u\n", e); });
  ArduinoOTA.begin();
}

void loop() {
  ArduinoOTA.handle();          // MUST be called often: no long delay()s

  if (millis() - lastBlink >= 500) {   // your own program goes here, non-blocking
    lastBlink = millis();
    digitalWrite(LED, !digitalRead(LED));
  }
}

Steps

  1. The first upload must be done over USB to put the OTA code into the chip.
  2. Open the Serial Monitor and note the IP address that is printed.
  3. In the Arduino IDE: Tools → Port → choose esp32diy-ota at 192.168.x.x under "Network ports" and click Upload. Enter the password when prompted.
  4. If the IDE does not show the network port (PC and ESP32 on different subnets, the router has "AP isolation" enabled, mDNS is blocked), use PlatformIO or call espota.py directly with the IP address (see below).

PlatformIO

[env:esp32dev]
platform = espressif32
board = esp32dev
framework = arduino
board_build.partitions = min_spiffs.csv   ; two ~1.9 MB app slots for OTA

upload_protocol = espota
upload_port = esp32diy-ota.local          ; or an IP address, e.g. 192.168.1.50
upload_flags =
  --auth=doi_mat_khau_nay

Upload over the network with the usual pio run -t upload. Or, with no IDE at all, you only need the compiled .bin:

python espota.py -i 192.168.1.50 -p 3232 --auth=change_this_password -f firmware.bin

espota.py lives in the tools folder of the ESP32 board package (packages/esp32/hardware/esp32/<version>/tools in your Arduino data folder).

Under the hood: the PC sends an invitation over UDP to port 3232 on the ESP32, then the ESP32 opens a TCP connection back to the PC to pull the firmware file. The PC's firewall therefore has to allow incoming TCP connections; otherwise you get errors like "No response from device".

Method 2: A web page to upload a .bin file

Handy when the device is already deployed and you want to update it from a browser, or let someone else do it. In the Arduino IDE use Sketch → Export Compiled Binary to get the .bin (use the file without the bootloader/partitions suffix, i.e. the one named sketch.ino.bin).

#include <WiFi.h>
#include <WebServer.h>
#include <Update.h>

const char* WIFI_SSID = "ten_wifi";
const char* WIFI_PASS = "mat_khau_wifi";
const char* WEB_USER  = "admin";
const char* WEB_PASS  = "doi_mat_khau_nay";

WebServer server(80);

const char PAGE[] PROGMEM =
  "<form method='POST' action='/update' enctype='multipart/form-data'>"
  "<input type='file' name='fw' accept='.bin'><input type='submit' value='Upload'></form>";

void setup() {
  Serial.begin(115200);
  WiFi.begin(WIFI_SSID, WIFI_PASS);
  while (WiFi.status() != WL_CONNECTED) delay(300);
  Serial.println(WiFi.localIP());

  server.on("/", HTTP_GET, []() {
    if (!server.authenticate(WEB_USER, WEB_PASS)) return server.requestAuthentication();
    server.send(200, "text/html", PAGE);
  });

  server.on("/update", HTTP_POST,
    []() {                                    // runs after the upload completes
      if (!server.authenticate(WEB_USER, WEB_PASS)) return server.requestAuthentication();
      bool ok = !Update.hasError();
      server.send(200, "text/plain", ok ? "OK, rebooting..." : "ERROR");
      if (ok) { delay(500); ESP.restart(); }
    },
    []() {                                    // runs for every uploaded chunk
      if (!server.authenticate(WEB_USER, WEB_PASS)) return;
      HTTPUpload& up = server.upload();
      if (up.status == UPLOAD_FILE_START) {
        Update.begin(UPDATE_SIZE_UNKNOWN);
      } else if (up.status == UPLOAD_FILE_WRITE) {
        Update.write(up.buf, up.currentSize);
      } else if (up.status == UPLOAD_FILE_END) {
        Update.end(true);                     // true = mark the new partition as the boot partition
      }
    });
  server.begin();
}

void loop() { server.handleClient(); }
Security: Basic Auth over HTTP is not encrypted, so the password can be sniffed on the network. Use it only on a trusted LAN and never expose this port to the Internet. The ElegantOTA library offers a nicer UI, but it relies on the same Update.h mechanism shown above.

Method 3: The device pulls updates from a server (HTTPS)

The right design when you have many devices: put firmware.bin and version.txt on a web server (GitHub Releases, Cloudflare R2, a VPS...) and have each device check the version periodically and update itself. No inbound port needs to be opened on the device.

#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <HTTPClient.h>
#include <HTTPUpdate.h>

const int   FW_VERSION = 3;                                    // increase on every release
const char* VER_URL    = "https://example.com/esp32diy/version.txt";   // file content: 4
const char* FW_URL     = "https://example.com/esp32diy/firmware.bin";
const char* ROOT_CA    = "-----BEGIN CERTIFICATE-----\n...\n-----END CERTIFICATE-----\n";

void checkForUpdate() {
  WiFiClientSecure client;
  client.setCACert(ROOT_CA);                  // authenticate the server; never use setInsecure() in production

  HTTPClient http;
  if (!http.begin(client, VER_URL)) return;
  int code = http.GET();
  int latest = (code == HTTP_CODE_OK) ? http.getString().toInt() : 0;
  http.end();
  if (latest <= FW_VERSION) return;           // already up to date

  t_httpUpdate_return r = httpUpdate.update(client, FW_URL);   // reboots by itself on success
  if (r == HTTP_UPDATE_FAILED)
    Serial.printf("Update failed %d: %s\n", httpUpdate.getLastError(), httpUpdate.getLastErrorString().c_str());
}

Common errors

SymptomCause and fix
No "Network ports" shownDifferent network, AP isolation, blocked mDNS. Use the IP with PlatformIO or espota.py.
Auth error (OTA_AUTH_ERROR)Wrong password.
Begin error (OTA_BEGIN_ERROR) or "Not enough space"The firmware is larger than the app partition, or a "No OTA" scheme is in use. Change the Partition Scheme (you must reflash over the cable once to apply the new partition table).
Connect error / "No response from device"A firewall blocks UDP 3232 or the reverse TCP connection to the PC. Allow the Arduino IDE/Python through the firewall.
Progress stalls at some % then a receive error (OTA_RECEIVE_ERROR)Weak WiFi signal or a supply that cannot deliver enough current while transmitting. Move closer to the router and use a better supply.
Update succeeds but you cannot OTA next timeThe new sketch lacks ArduinoOTA.begin()/handle(), or loop() is blocked by a long delay.
Device boot-loops or hangs after OTAThe new firmware is faulty. The Arduino core's default bootloader does not enable automatic rollback, so reflash over the cable. With ESP-IDF you can enable CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE.

Security and reliability notes

Summary