Welcome to ESP32 Core Board repository
11. WIFI OTA Upgrade
WIFI-OTA Upgrade Experiment
WIFI-OTA Upgrade Experiment1. WIFI-OTA Overview2. Core Concepts2.1 OTA Partition Layout2.2 Update Library Three-Step Process2.3 Streaming Download2.4 RGB LED Status Indicator3. Hardware Dependencies4. Project Architecture and Flow5. Source Code Details5.1 Configuration and Global Variables5.2 connectWiFi() — WiFi Connection with Retry5.3 setLed() — RGB LED Wrapper5.4 printProgress() — Progress Bar Print5.5 Version Management (NVS)5.6 checkUpdate() — OTA Main Flow5.7 doOTA() — Streaming Firmware Download and Write5.8 compareVersion() — Semantic Version Comparison6. Operation Flow6.1 Tool Setup6.2 Operation Steps6.3 Verification Methods7. FAQ
1. WIFI-OTA Overview
OTA (Over-The-Air) is a core maintenance capability for IoT devices—downloading new firmware over WiFi, writing it to the OTA partition in Flash, then automatically rebooting to run the new firmware. No physical USB cable needed, no JTAG programmer required; products can still be updated continuously after deployment.
Importance: OTA is the "lifeline" for mass-produced IoT products—without OTA, every bug fix or feature update requires manual disassembly and flashing, which is unacceptable. Smart home, industrial sensing, agricultural monitoring, and all embedded devices requiring remote deployment rely on OTA for continuous iteration.
This experiment powers on, fetches version.txt from the server via HTTP, compares it with the local version stored in NVS; if the server version is newer, it automatically downloads the .bin firmware and writes it to the OTA partition in Flash, then reboots to run the new firmware. During the upgrade process, the WS2812B RGB LED provides visual feedback: Red (upgrading) → Green (write complete) → Blue (successful reboot).
Typical Application Scenarios:
| Application Type | Example |
|---|---|
| Batch device upgrades | Remote push of bug fixes after factory shipment |
| Unattended devices | Field sensors, rooftop weather stations without USB updates |
| Rapid iteration | WiFi OTA eliminates repeated USB plugging during development |
2. Core Concepts
2.1 OTA Partition Layout
The ESP32-S3 default partition table contains two app partitions (ota_0 + ota_1) and an otadata partition, which records which partition to boot from:
New firmware written to ota_1 → Update.end() verifies SHA256 → Updates otadata boot flag → ESP.restart() boots from ota_1
During the next upgrade, it alternately writes to the other partition (ota_0), implementing ping-pong upgrades.
2.2 Update Library Three-Step Process
| Step | API | Function |
|---|---|---|
| ① Initialize | Update.begin(size) | Erases target partition, prepares for writing |
| ② Stream Write | Update.write(buf, len) | Write to Flash while downloading (no RAM usage) |
| ③ Verify Complete | Update.end() | SHA256 verification + update boot flag, returns true on success |
2.3 Streaming Download
ESP32 only has ~520KB SRAM, while firmware is typically >1MB. You cannot read the entire firmware into RAM first then write to Flash—you must read from HTTP stream and write via Update.write() simultaneously. The code uses http.getStream().readBytes() to read 2KB data chunks, write them, then continue to the next chunk until size reaches zero.
The 1.5MB limit (1024 * 1500) provides safety margin for other partitions like SPIFFS and NVS.
2.4 RGB LED Status Indicator
The upgrade process provides visual feedback via the onboard WS2812B, no need to stare at the serial port:
| LED Color | Stage | Meaning |
|---|---|---|
| Red | Before doOTA() starts | Firmware downloading and writing, do not power off |
| Green | When Update.end() returns true | Flash write + SHA256 verification passed |
| Blue | After saveNewVersion() | Upgrade succeeded, about to reboot |
3. Hardware Dependencies
| Dependency | Description |
|---|---|
| Network Connection | WiFi 2.4GHz, WIFI-STA mode, HTTP server required on the same local network |
| WS2812B | GPIO 48 driven, upgrade status visualization |
| Flash Partition | OTA-compatible partition table required (e.g., Minimal SPIFFS), containing ota_0 partition |
| Library Dependencies | WiFi, HTTPClient, Update, Preferences (all built-in); Adafruit_NeoPixel (installed via library manager) |
| HTTP Server | PC hosts version.txt + .bin firmware, project provides OTA_HTTP_Server.bat + OTA_Server.py for one-click HTTP server startup (adapted from ESP-IDF OTA plugin: supports Range requests, CORS cross-domain, automatic LAN IP detection) |
The onboard WS2812B is on GPIO 48; if using a different development board, modify the
RGB_PINmacro.
4. Project Architecture and Flow
xsetup()├─ prefs.begin("ota_config") // Open NVS namespace (stores local version)├─ pixels.begin() + clear() // Initialize WS2812B RGB LED├─ connectWiFi() // Connect to router (with retry)└─ checkUpdate() // OTA main logiccheckUpdate():├─ getLocalVersion() // Read local version from NVS, write "1.0.0" on first run├─ HTTP GET version.txt // Fetch server version├─ compareVersion(server, local) > 0? // Semantic version comparison│ ├─ setLed(255,0,0) Red LED // Upgrading, do not power off│ └─ doOTA() // Download + Write Flash + progress bar│ ├─ HTTP GET firmware.bin (streaming, external WiFiClient)│ ├─ Update.begin(totalSize) → write(buf) loop│ ├─ printProgress() refreshes progress bar every 10%│ └─ Returns true/false│ └─ if ok:│ ├─ setLed(0,255,0) Green LED // Write verification passed│ ├─ saveNewVersion(serverVer) // Write new version to NVS│ ├─ setLed(0,0,255) Blue LED // Upgrade succeeded│ └─ ESP.restart() // Soft reset to boot new firmwareloop()└─ delay(10000) // Idle loop
5. Source Code Details
Complete source code: Source code → Arduino → 3.Network Communication → WiFi_OTA_Automatic → WiFi_OTA_Automatic.ino
5.1 Configuration and Global Variables
The header includes WiFi, HTTP, OTA, NVS, and RGB LED five modules. WiFiClient client is an external TCP client used for streaming firmware download in doOTA(). Version check includes 3 retries (consistent with ESP-IDF), tolerating network jitter. OTA server URL must match the IP printed by OTA_Server.py.
xxxxxxxxxx
// ==================== Config Section / Configuration ====================const char* WIFI_SSID = "Yahboom2";const char* WIFI_PASS = "yahboom890729";
// OTA server URL — Replace with IP printed by OTA_Server.py after running it//192.168.11.183:8080/version.txt"//192.168.11.183:8080/WiFi_OTA_Automatic.ino.bin"
// Default version in NVS// WS2812B pin// Number of LEDs// Version check retry count// Retry interval ms
Preferences prefs; // NVS storage objectWiFiClient client; // TCP clientAdafruit_NeoPixel pixels(LED_NUM, RGB_PIN, NEO_GRB + NEO_KHZ800);5.2 connectWiFi() — WiFi Connection with Retry
The while(true) infinite loop ensures OTA devices never give up reconnecting after network loss. Each attempt calls WiFi.disconnect(true) first to clear cache. 10 second timeout + 15 second retry interval prevents high-frequency reconnection from exhausting router resources.
xxxxxxxxxxvoid connectWiFi() { const int TIMEOUT_MS = 10000;
int attempt = 0; while (true) { attempt++; Serial.printf("Connecting WiFi: %s (Attempt %d)\n", WIFI_SSID, attempt); WiFi.disconnect(true); // Disconnect, clear cache delay(500); WiFi.begin(WIFI_SSID, WIFI_PASS);
unsigned long startTime = millis(); while (WiFi.status() != WL_CONNECTED && (millis() - startTime) < TIMEOUT_MS) { delay(500); Serial.print("."); }
if (WiFi.status() == WL_CONNECTED) { Serial.println("\nWiFi Connected successfully"); Serial.print("Device IP: "); Serial.println(WiFi.localIP()); Serial.print("Version URL: "); Serial.println(VERSION_URL); return; }
Serial.println("\nWiFi Connection timed out! Retrying in 15s..."); delay(15000); }}Unlike previous experiments, this uses
while(true)+ 15 second retry interval to ensure OTA devices automatically reconnect after network recovery.
5.3 setLed() — RGB LED Wrapper
Combines two Adafruit_NeoPixel calls (set color + refresh) into one function. The (r, g, b) tuple directly controls the onboard WS2812B color.
xxxxxxxxxxvoid setLed(uint8_t r, uint8_t g, uint8_t b) { pixels.setPixelColor(0, pixels.Color(r, g, b)); // Set LED #0 color pixels.show(); // Transmit to WS2812B}5.4 printProgress() — Progress Bar Print
Draws an ASCII progress bar on serial port to visually show firmware download progress.
xxxxxxxxxxvoid printProgress(int percent) { const int barWidth = 40; // Progress bar width int filled = barWidth * percent / 100; // Number of filled blocks Serial.print("["); for (int i = 0; i < barWidth; i++) { if (i < filled) Serial.print("="); else if (i == filled) Serial.print(">"); else Serial.print(" "); } Serial.printf("] %3d%%\n", percent); // Percentage + newline}Output: [==========> ] 25%
>marks the current progress position, completed portions use=, remaining uses space. 40 characters wide, refreshes every 10%.
5.5 Version Management (NVS)
NVS (Non-Volatile Storage) persists version numbers in Flash, surviving power loss. Writes default version 1.0.0 on first run.
xxxxxxxxxxString getLocalVersion() { if (!prefs.isKey("ver")) { // Write default if key missing prefs.putString("ver", DEFAULT_VERSION); } return prefs.getString("ver"); // Read version from NVS}
void saveNewVersion(String v) { prefs.putString("ver", v); // Write new version to NVS Serial.println("New version saved to Flash");}5.6 checkUpdate() — OTA Main Flow
Fetches server version, compares with local, decides whether to trigger OTA. Consistent with ESP-IDF, includes 3 retries for network jitter tolerance.
xxxxxxxxxxvoid checkUpdate() { if (WiFi.status() != WL_CONNECTED) return; // Skip if WiFi not connected
String local = getLocalVersion(); Serial.printf("Local version: %s\n", local.c_str());
HTTPClient http; http.setFollowRedirects(HTTPC_STRICT_FOLLOW_REDIRECTS); http.setConnectTimeout(5000); // 5s connect timeout
bool gotVersion = false; String serverVer; for (int retry = 0; retry < OTA_RETRY_MAX; retry++) { if (!http.begin(VERSION_URL)) { Serial.printf("Version check failed (retry %d/%d)\n", retry + 1, OTA_RETRY_MAX); } else { int code = http.GET(); if (code == HTTP_CODE_OK) { serverVer = http.getString(); // Read server version string serverVer.trim(); // Trim whitespace gotVersion = true; http.end(); break; } Serial.printf("HTTP code: %d (retry %d/%d)\n", code, retry + 1, OTA_RETRY_MAX); http.end(); } delay(OTA_RETRY_WAIT); // Wait before retry }
if (!gotVersion) { Serial.println("Version check failed after all retries"); return; }
Serial.printf("Server version: %s\n", serverVer.c_str());
if (compareVersion(serverVer, local) > 0) { // Server version is newer Serial.println("New version found! Start upgrading..."); setLed(255, 0, 0); // Red LED — updating, don't power off if (doOTA()) { setLed(0, 255, 0); // Green LED — firmware written delay(1000); saveNewVersion(serverVer); setLed(0, 0, 255); // Blue LED — upgrade succeeded Serial.println("Upgrade succeeded! Restarting..."); delay(2000); ESP.restart(); // Soft reset, boot new firmware } else { Serial.println("Upgrade failed"); } } else { Serial.println("Already the latest version"); }}
OTA_RETRY_MAX=3is consistent with ESP-IDF OTA routine retry count.OTA_RETRY_WAIT=2000msgives the server enough processing time. Afterhttp.GET()fetchesversion.txtcontent,trim()removes line breaks.
5.7 doOTA() — Streaming Firmware Download and Write
Four-step flow: HTTP GET to fetch firmware → Update.begin() to erase partition → 2KB chunked streaming write to Flash (refresh progress bar every 10%) → Update.end() SHA256 verification. Never loads complete firmware into RAM.
xxxxxxxxxxbool doOTA() { HTTPClient http; http.setFollowRedirects(HTTPC_STRICT_FOLLOW_REDIRECTS);
if (!http.begin(client, FIRMWARE_URL)) { // Streaming download via external WiFiClient Serial.println("Failed to connect to firmware server"); return false; }
int code = http.GET(); if (code != HTTP_CODE_OK) { Serial.printf("Firmware download failed, HTTP code: %d, error: %s\n", code, http.errorToString(code).c_str()); http.end(); return false; }
int totalSize = http.getSize(); // Firmware size from Content-Length Serial.printf("Firmware size: %d bytes\n", totalSize);
if (totalSize > 1024 * 1500) { // 1.5MB safety limit Serial.println("Firmware too large, partition cannot fit it"); http.end(); return false; }
Update.begin(totalSize); // Init OTA write, erase partition
uint8_t buf[2048]; // 2KB buffer, flash page-aligned int readed, downloaded = 0; int lastPercent = -1; // Last printed percent, avoid redundant print
while (http.connected() && totalSize > 0) { // Streaming download loop readed = http.getStream().readBytes(buf, sizeof(buf)); if (readed > 0) { Update.write(buf, readed); // Write to flash totalSize -= readed; // Remaining bytes downloaded += readed; } int percent = (totalSize <= 0) ? 100 : (downloaded * 100 / (downloaded + totalSize)); if (percent != lastPercent && percent % 10 == 0) { // Refresh every 10% printProgress(percent); lastPercent = percent; } } printProgress(100); // Ensure 100% shown Serial.println();
bool ok = Update.end(); // Finalize, SHA256 verify http.end(); return ok;}
totalSizetracks remaining bytes,downloadedtracks downloaded bytes.lastPercentprevents printing the same percentage repeatedly. CallsprintProgress()every 10%, forces printing100%after loop ends to prevent incomplete progress bar if loop exits early.
5.8 compareVersion() — Semantic Version Comparison
Uses sscanf to parse MAJOR.MINOR.PATCH three-part numbers, comparing segment by segment. Return value >0 means A is newer than B, <0 means A is older, 0 means equal.
xxxxxxxxxxint compareVersion(String a, String b) { int va[3] = {0}, vb[3] = {0}; // major, minor, patch sscanf(a.c_str(), "%d.%d.%d", &va[0], &va[1], &va[2]); sscanf(b.c_str(), "%d.%d.%d", &vb[0], &vb[1], &vb[2]);
if (va[0] > vb[0]) return 1; // A major > B major if (va[0] < vb[0]) return -1; if (va[1] > vb[1]) return 1; // A minor > B minor if (va[1] < vb[1]) return -1; if (va[2] > vb[2]) return 1; // A patch > B patch if (va[2] < vb[2]) return -1; return 0; // Versions equal}Compares
MAJOR.MINOR.PATCHsegment by segment. Return value >0 means A is newer than B, <0 means A is older, 0 means equal.
6. Operation Flow
6.1 Tool Setup
Arduino Flashing Flow: See Arduino → 1.Before Development → 2.Build and Flash.
① Install Dependent Libraries
Arduino IDE → Tools → Manage Libraries → Search Adafruit NeoPixel → Install.
② Modify WiFi SSID and Password
Change WIFI_SSID and WIFI_PASS in the code to your actual router credentials.
③ Compile and Export bin Firmware
Arduino IDE → Sketch → Export Compiled Binary (or shortcut Ctrl+Alt+S). After compilation, the .bin file is located in build/esp32.esp32.esp32s3/ within the project directory, named WiFi_OTA_Automatic.ino.bin.


Copy this
.binfile to theOTA_UPDATAfolder, together withversion.txtIn
version.txt, write a version number higher than1.0.0(e.g.,1.8.2)

④ Initial Flash
Use USB to flash the current code to ESP32-S3 (local version 1.0.0).
6.2 Operation Steps
Step 1: Start HTTP Server
Confirm the .bin firmware and version.txt are in the OTA_UPDATA folder (see Step ③ in 6.1).

Double-click to start OTA_Server.py.
Detect Python environment
Get local LAN IP
Configure Windows Firewall (open port 8080)
Run
OTA_Server.pyHTTP server (adapted from ESP-IDF OTA plugin, supports Range requests, CORS cross-domain)
The server prints the complete URLs for version.txt and .bin firmware:

OTA_Server.pyis adapted from ESP-IDF OTA pluginota_server_linux.py, supports HTTP Range requests (206 Partial Content), providing compatibility for future extracting version numbers directly from firmware binary header. If Windows Firewall popup appears, click "Allow access". If Python is not installed prompt appears, install Python 3 first.
Step 2: Modify Server IP, Initial Flash
Open Arduino IDE, change the IP address inside VERSION_URL and FIRMWARE_URL to the actual IP output by the python script; after compilation, flash to ESP32-S3 via USB.
It is recommended to use WiFi network preferably, try to avoid using ethernet cable; if needed, you can disable local ethernet adapter.
Step 3: Observe OTA Auto Upgrade
After flashing, open Serial Monitor (baud rate 115200), ESP32 automatically connects to WiFi and checks version. If server version is newer, it automatically downloads firmware and prints progress bar:
xxxxxxxxxxConnecting WiFi: Yahboom2 (Attempt 1)WiFi Connected successfullyDevice IP: 192.168.11.229Local version: 1.0.0Server version: 1.8.2New version found! Start upgrading...Firmware size: 1048576 bytes[========================================] 100%New version saved to FlashUpgrade succeeded! Restarting...

The onboard RGB LED changes in sequence: Red (downloading) → Green (verification passed) → Blue (about to reboot).
The entire process the onboard RGB LED changes: Red → Green → Blue → Reboot.
Step 4: Verify Upgrade Success
After reboot, Serial prints Local version: 1.8.2, matching server version, and no longer triggers upgrade (prints Already the latest version). If firmware runtime behavior differs from old version (you can intentionally change print content in setup()), it also confirms the upgrade took effect.

6.3 Verification Methods
| Operation | Expected Result |
|---|---|
| Server version > Local version | Red→Green→Blue LED, auto download and reboot |
| Server version = Local version | Prints "Already the latest version", no upgrade |
| Server unreachable | After 3 retries, prints failure message, skips upgrade (consistent with ESP-IDF retry strategy) |
| Firmware server unreachable | Version check passes but doOTA() returns false |
7. FAQ
| Symptom | Cause | Solution |
|---|---|---|
Update.begin() fails | Partition table doesn't support OTA | Select board option with OTA partition in Arduino IDE (e.g., Minimal SPIFFS) |
Update.end() verification fails | Firmware download incomplete or corrupted | Check network stability, reduce WiFi interference |
| Still running old firmware after reboot | otadata not updated | Confirm Update.end() returned true |
| Version comparison always triggers upgrade | version.txt trailing newline causes sscanf parsing anomaly | Code already handles this with serverVer.trim() |
http.GET() returns -1 or retry 3 times fails | Server not started or wrong IP | Verify by browsing to http://<IP>:8080/version.txt; confirm using OTA_Server.py not python -m http.server |
Compilation error: Adafruit_NeoPixel.h not found | Library not installed | Search and install in Arduino IDE Library Manager |