Flash ESP-32 Wirelessly Through WIFI – OTA

Modern Gaming Cover YouTube Channel Art
This content provide you Experience

This technique is applicable in numerous projects where physical connections are not necessary for flashing, allowing the user to simply be in close to the ESP32 controller and complete the flashing process wirelessly, eliminating the need for cables.

Convenience: By eliminating the requirement for physical connections and cords, flashing the ESP-32 remotely through WIFI is substantially more easy and user-friendly.

Quicker transfer rates: Compared to serial connections, WIFI transfer rates are often substantially quicker, which helps speed up the flashing procedure.

Remote access: WIFI enables remote flashing of an ESP-32, which is particularly helpful when the device is situated in a difficult-to-reach or distant area.

Support for multiple devices: When flashing an ESP-32 wirelessly, it is possible to flash several devices at once, which helps speed up production and save time.

Versatility: WIFI flashing is a flexible solution for people that operate with various types of hardware since it is compatible with a large range of devices.

STEP-1> Getting start with esp32

STEP2- Install Libraries

Go -to Tools >> Manage Library >> Search these libraries

  • Wifi.h
  • WifiClint
  • WebServer
  • ESPmDNS

STEP2- UPLOAD OTA – Code

First upload this OTA code to enable the OTA feature in your ESP32

// OTA code for Enabaling OTA feaures


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

const char* host = "esp32"; // #define WIFI_SSID "TP-Link_B8E6"
//#define WIFI_PASSWORD "59988083"
const char* ssid = "Your SSID";
const char* password = "Your Password";

WebServer Server_Ota(80);

/*
 * Login page
 */

const char* loginIndex =
 "<form name='loginForm'>"
    "<table width='20%' bgcolor='A09F9F' align='center'>"
        "<tr>"
            "<td colspan=2>"
                "<center><font size=4><b>ESP32 Login Page</b></font></center>"
                "<br>"
            "</td>"
            "<br>"
            "<br>"
        "</tr>"
        "<tr>"
             "<td>Username:</td>"
             "<td><input type='text' size=25 name='userid'><br></td>"
        "</tr>"
        "<br>"
        "<br>"
        "<tr>"
            "<td>Password:</td>"
            "<td><input type='Password' size=25 name='pwd'><br></td>"
            "<br>"
            "<br>"
        "</tr>"
        "<tr>"
            "<td><input type='submit' onclick='check(this.form)' value='Login'></td>"
        "</tr>"
    "</table>"
"</form>"
"<script>"
    "function check(form)"
    "{"
    "if(form.userid.value=='Elconics' && form.pwd.value=='Elconics@123')"
    "{"
    "window.open('/Server_OtaIndex')"
    "}"
    "else"
    "{"
    " alert('Error Password or Username')/*displays error message*/"
    "}"
    "}"
"</script>";

/*
 * Server Index Page
 */

const char* Server_OtaIndex =
"<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>"
"<form method='POST' action='#' enctype='multipart/form-data' id='upload_form'>"
   "<input type='file' name='update'>"
        "<input type='submit' value='Update'>"
    "</form>"
 "<div id='prg'>progress: 0%</div>"
 "<script>"
  "$('form').submit(function(e){"
  "e.preventDefault();"
  "var form = $('#upload_form')[0];"
  "var data = new FormData(form);"
  " $.ajax({"
  "url: '/update',"
  "type: 'POST',"
  "data: data,"
  "contentType: false,"
  "processData:false,"
  "xhr: function() {"
  "var xhr = new window.XMLHttpRequest();"
  "xhr.upload.addEventListener('progress', function(evt) {"
  "if (evt.lengthComputable) {"
  "var per = evt.loaded / evt.total;"
  "$('#prg').html('progress: ' + Math.round(per*100) + '%');"
  "}"
  "}, false);"
  "return xhr;"
  "},"
  "success:function(d, s) {"
  "console.log('success!')"
 "},"
 "error: function (a, b, c) {"
 "}"
 "});"
 "});"
 "</script>";

/*
 * setup function
 */
void setup(void) {
  Serial.begin(115200);

  // Connect to WiFi network
  WiFi.begin(ssid, password);
  Serial.println("");

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  /*use mdns for host name resolution*/
  if (!MDNS.begin(host)) { //http://esp32.local
    Serial.println("Error setting up MDNS responder!");
    while (1) {
      delay(1000);
    }
  }
  Serial.println("mDNS responder started");
  /*return index page which is stored in serverIndex */
  Server_Ota.on("/", HTTP_GET, []() {
    Server_Ota.sendHeader("Connection", "close");
    Server_Ota.send(200, "text/html", loginIndex);
  });
  Server_Ota.on("/Server_OtaIndex", HTTP_GET, []() {
    Server_Ota.sendHeader("Connection", "close");
    Server_Ota.send(200, "text/html", Server_OtaIndex);
  });
  /*handling uploading firmware file */
  Server_Ota.on("/update", HTTP_POST, []() {
    Server_Ota.sendHeader("Connection", "close");
    Server_Ota.send(200, "text/plain", (Update.hasError()) ? "FAIL" : "OK");
    ESP.restart();
  }, []() {
    HTTPUpload& upload = Server_Ota.upload();
    if (upload.status == UPLOAD_FILE_START) {
      Serial.printf("Update: %s\n", upload.filename.c_str());
      if (!Update.begin(UPDATE_SIZE_UNKNOWN)) { //start with max available size
        Update.printError(Serial);
      }
    } else if (upload.status == UPLOAD_FILE_WRITE) {
      /* flashing firmware to ESP*/
      if (Update.write(upload.buf, upload.currentSize) != upload.currentSize) {
        Update.printError(Serial);
      }
    } else if (upload.status == UPLOAD_FILE_END) {
      if (Update.end(true)) { //true to set the size to the current progress
        Serial.printf("Update Success: %u\nRebooting...\n", upload.totalSize);
      } else {
        Update.printError(Serial);
      }
    }
  });
  Server_Ota.begin();
}

void loop(void) {
  Server_Ota.handleClient();
  delay(1);
}

Edit your login-id and Password here in code under <script> function .

"if(form.userid.value=='Your_user_name ' && form.pwd.value=='Password')"

After sucessfully upload this code >> Go to serial monitor to and copy the IP Address.

Paste this IP – address in browser >> Make sure your system and esp32 connected to same network.

Enter your username and password you have entered in code >> Every time you flashing esp32 wirelessly you need to enter this username and password.

STEP4- OTA For Blinking LED

Copy this code and paste it in arduino ide .

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

const char* host = "esp32"; // #define WIFI_SSID "TP-Link_B8E6"
//#define WIFI_PASSWORD "59988083"
const char* ssid = "Elconics";
const char* password = "Elconics@789";
#define LED 2

WebServer Server_Ota(80);

/*
 * Login page
 */

const char* loginIndex =
 "<form name='loginForm'>"
    "<table width='20%' bgcolor='A09F9F' align='center'>"
        "<tr>"
            "<td colspan=2>"
                "<center><font size=4><b>ESP32 Login Page</b></font></center>"
                "<br>"
            "</td>"
            "<br>"
            "<br>"
        "</tr>"
        "<tr>"
             "<td>Username:</td>"
             "<td><input type='text' size=25 name='userid'><br></td>"
        "</tr>"
        "<br>"
        "<br>"
        "<tr>"
            "<td>Password:</td>"
            "<td><input type='Password' size=25 name='pwd'><br></td>"
            "<br>"
            "<br>"
        "</tr>"
        "<tr>"
            "<td><input type='submit' onclick='check(this.form)' value='Login'></td>"
        "</tr>"
    "</table>"
"</form>"
"<script>"
    "function check(form)"
    "{"
    "if(form.userid.value=='Elconics' && form.pwd.value=='Elconics@123')"
    "{"
    "window.open('/Server_OtaIndex')"
    "}"
    "else"
    "{"
    " alert('Error Password or Username')/*displays error message*/"
    "}"
    "}"
"</script>";

/*
 * Server Index Page
 */

const char* Server_OtaIndex =
"<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>"
"<form method='POST' action='#' enctype='multipart/form-data' id='upload_form'>"
   "<input type='file' name='update'>"
        "<input type='submit' value='Update'>"
    "</form>"
 "<div id='prg'>progress: 0%</div>"
 "<script>"
  "$('form').submit(function(e){"
  "e.preventDefault();"
  "var form = $('#upload_form')[0];"
  "var data = new FormData(form);"
  " $.ajax({"
  "url: '/update',"
  "type: 'POST',"
  "data: data,"
  "contentType: false,"
  "processData:false,"
  "xhr: function() {"
  "var xhr = new window.XMLHttpRequest();"
  "xhr.upload.addEventListener('progress', function(evt) {"
  "if (evt.lengthComputable) {"
  "var per = evt.loaded / evt.total;"
  "$('#prg').html('progress: ' + Math.round(per*100) + '%');"
  "}"
  "}, false);"
  "return xhr;"
  "},"
  "success:function(d, s) {"
  "console.log('success!')"
 "},"
 "error: function (a, b, c) {"
 "}"
 "});"
 "});"
 "</script>";
 bool STATE = LOW;
/*
 * setup function
 */
 
void setup(void) {
  Serial.begin(115200);
  pinMode(LED,OUTPUT);
  
  // Connect to WiFi network
  WiFi.begin(ssid, password);
  Serial.println("");

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  /*use mdns for host name resolution*/
  if (!MDNS.begin(host)) { //http://esp32.local
    Serial.println("Error setting up MDNS responder!");
    while (1) {
      delay(1000);
    }
  }
  Serial.println("mDNS responder started");
  /*return index page which is stored in serverIndex */
  Server_Ota.on("/", HTTP_GET, []() {
    Server_Ota.sendHeader("Connection", "close");
    Server_Ota.send(200, "text/html", loginIndex);
  });
  Server_Ota.on("/Server_OtaIndex", HTTP_GET, []() {
    Server_Ota.sendHeader("Connection", "close");
    Server_Ota.send(200, "text/html", Server_OtaIndex);
  });
  /*handling uploading firmware file */
  Server_Ota.on("/update", HTTP_POST, []() {
    Server_Ota.sendHeader("Connection", "close");
    Server_Ota.send(200, "text/plain", (Update.hasError()) ? "FAIL" : "OK");
    ESP.restart();
  }, []() {
    HTTPUpload& upload = Server_Ota.upload();
    if (upload.status == UPLOAD_FILE_START) {
      Serial.printf("Update: %s\n", upload.filename.c_str());
      if (!Update.begin(UPDATE_SIZE_UNKNOWN)) { //start with max available size
        Update.printError(Serial);
      }
    } else if (upload.status == UPLOAD_FILE_WRITE) {
      /* flashing firmware to ESP*/
      if (Update.write(upload.buf, upload.currentSize) != upload.currentSize) {
        Update.printError(Serial);
      }
    } else if (upload.status == UPLOAD_FILE_END) {
      if (Update.end(true)) { //true to set the size to the current progress
        Serial.printf("Update Success: %u\nRebooting...\n", upload.totalSize);
      } else {
        Update.printError(Serial);
      }
    }
  });
  Server_Ota.begin();
}

void loop(void) {
 
  digitalWrite(LED,HIGH);
  delay(1000);
   digitalWrite(LED,LOW);
  delay(1000);
 //STATE!=STATE;
  delay(1000);
  Server_Ota.handleClient();
  delay(1);
}

Go-to->>Sketch >> Compiled binary

After compilation done >> Press Ctrl+k >> You will get bin file choose this file and click on update.

After completing this progress to 100% >> You will see Your inbuild LED stsrts Blinking

STEP 5 – OTA – For servo sweep test

Follow this same step- and choose the file and update bin file of this code.

#include <WiFi.h>
#include <WiFiClient.h>
#include <WebServer.h>
#include <ESPmDNS.h>
#include <Update.h>
#include <Servo.h>
// Servo Motor Code
Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards

int pos = 0;    // variable to store the servo position


const char* host = "esp32"; // #define WIFI_SSID "TP-Link_B8E6"
//#define WIFI_PASSWORD "59988083"
const char* ssid = "Elconics";
const char* password = "Elconics@789";


WebServer Server_Ota(80);

/*
 * Login page
 */

const char* loginIndex =
 "<form name='loginForm'>"
    "<table width='20%' bgcolor='A09F9F' align='center'>"
        "<tr>"
            "<td colspan=2>"
                "<center><font size=4><b>ESP32 Login Page</b></font></center>"
                "<br>"
            "</td>"
            "<br>"
            "<br>"
        "</tr>"
        "<tr>"
             "<td>Username:</td>"
             "<td><input type='text' size=25 name='userid'><br></td>"
        "</tr>"
        "<br>"
        "<br>"
        "<tr>"
            "<td>Password:</td>"
            "<td><input type='Password' size=25 name='pwd'><br></td>"
            "<br>"
            "<br>"
        "</tr>"
        "<tr>"
            "<td><input type='submit' onclick='check(this.form)' value='Login'></td>"
        "</tr>"
    "</table>"
"</form>"
"<script>"
    "function check(form)"
    "{"
    "if(form.userid.value=='Elconics' && form.pwd.value=='Elconics@123')"
    "{"
    "window.open('/Server_OtaIndex')"
    "}"
    "else"
    "{"
    " alert('Error Password or Username')/*displays error message*/"
    "}"
    "}"
"</script>";

/*
 * Server Index Page
 */

const char* Server_OtaIndex =
"<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>"
"<form method='POST' action='#' enctype='multipart/form-data' id='upload_form'>"
   "<input type='file' name='update'>"
        "<input type='submit' value='Update'>"
    "</form>"
 "<div id='prg'>progress: 0%</div>"
 "<script>"
  "$('form').submit(function(e){"
  "e.preventDefault();"
  "var form = $('#upload_form')[0];"
  "var data = new FormData(form);"
  " $.ajax({"
  "url: '/update',"
  "type: 'POST',"
  "data: data,"
  "contentType: false,"
  "processData:false,"
  "xhr: function() {"
  "var xhr = new window.XMLHttpRequest();"
  "xhr.upload.addEventListener('progress', function(evt) {"
  "if (evt.lengthComputable) {"
  "var per = evt.loaded / evt.total;"
  "$('#prg').html('progress: ' + Math.round(per*100) + '%');"
  "}"
  "}, false);"
  "return xhr;"
  "},"
  "success:function(d, s) {"
  "console.log('success!')"
 "},"
 "error: function (a, b, c) {"
 "}"
 "});"
 "});"
 "</script>";
 bool STATE = LOW;
/*
 * setup function
 */
 
void setup(void) {
  Serial.begin(115200);
  myservo.attach(26);  // attaches the servo on pin 13 to the servo object
  
  // Connect to WiFi network
  WiFi.begin(ssid, password);
  Serial.println("");

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  /*use mdns for host name resolution*/
  if (!MDNS.begin(host)) { //http://esp32.local
    Serial.println("Error setting up MDNS responder!");
    while (1) {
      delay(1000);
    }
  }
  Serial.println("mDNS responder started");
  /*return index page which is stored in serverIndex */
  Server_Ota.on("/", HTTP_GET, []() {
    Server_Ota.sendHeader("Connection", "close");
    Server_Ota.send(200, "text/html", loginIndex);
  });
  Server_Ota.on("/Server_OtaIndex", HTTP_GET, []() {
    Server_Ota.sendHeader("Connection", "close");
    Server_Ota.send(200, "text/html", Server_OtaIndex);
  });
  /*handling uploading firmware file */
  Server_Ota.on("/update", HTTP_POST, []() {
    Server_Ota.sendHeader("Connection", "close");
    Server_Ota.send(200, "text/plain", (Update.hasError()) ? "FAIL" : "OK");
    ESP.restart();
  }, []() {
    HTTPUpload& upload = Server_Ota.upload();
    if (upload.status == UPLOAD_FILE_START) {
      Serial.printf("Update: %s\n", upload.filename.c_str());
      if (!Update.begin(UPDATE_SIZE_UNKNOWN)) { //start with max available size
        Update.printError(Serial);
      }
    } else if (upload.status == UPLOAD_FILE_WRITE) {
      /* flashing firmware to ESP*/
      if (Update.write(upload.buf, upload.currentSize) != upload.currentSize) {
        Update.printError(Serial);
      }
    } else if (upload.status == UPLOAD_FILE_END) {
      if (Update.end(true)) { //true to set the size to the current progress
        Serial.printf("Update Success: %u\nRebooting...\n", upload.totalSize);
      } else {
        Update.printError(Serial);
      }
    }
  });
  Server_Ota.begin();
}

void loop(void) {
 
for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
    // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
  for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
 
  Server_Ota.handleClient();
  delay(1);
}

Leave a Comment

Your email address will not be published. Required fields are marked *

Related post