Yarana Iot Guru
Published © MIT

Change WiFi on ESP32 Without Re-uploading Code

Allow users to change Wi-Fi credentials at runtime using a captive-portal — no code re-upload needed

BeginnerProtip8 hours63
Change WiFi on ESP32 Without Re-uploading Code

Things used in this project

Story

Read more

Code

💻 Arduino Code

C/C++
#include <WiFi.h>
#include <WebServer.h>
#include <Preferences.h>

Preferences preferences;
WebServer server(80);

String ssid = "";
String password = "";

void handleRoot() {
  String html = "<h2>ESP32 WiFi Setup Portal</h2><form action='/save'><input name='ssid' placeholder='SSID'><br><input name='pass' placeholder='Password'><br><input type='submit'></form>";
  server.send(200, "text/html", html);
}

void handleSave() {
  ssid = server.arg("ssid");
  password = server.arg("pass");
  
  preferences.begin("wifi-config", false);
  preferences.putString("ssid", ssid);
  preferences.putString("pass", password);
  preferences.end();
  
  String html = "<h3>Saved Successfully! Rebooting...</h3>";
  server.send(200, "text/html", html);
  delay(2000);
  ESP.restart();
}

void setup() {
  Serial.begin(115200);
  preferences.begin("wifi-config", true);
  ssid = preferences.getString("ssid", "");
  password = preferences.getString("pass", "");
  preferences.end();

  if (ssid != "") {
    WiFi.begin(ssid.c_str(), password.c_str());
    Serial.println("Connecting to saved WiFi...");
    for (int i = 0; i < 20; i++) {
      if (WiFi.status() == WL_CONNECTED) break;
      delay(500);
      Serial.print(".");
    }
  }

  if (WiFi.status() != WL_CONNECTED) {
    WiFi.softAP("ESP32_Setup");
    server.on("/", handleRoot);
    server.on("/save", handleSave);
    server.begin();
    Serial.println("AP Mode: ESP32_Setup");
  }
}

void loop() {
  server.handleClient();
}

Credits

Yarana Iot Guru
28 projects • 0 followers
Yarana Iot Guru Yarana IoT Guru: Arduino, ESP32, GSM, NodeMCU & more. Projects, Tutorials & App Development. Innovate with us!
Thanks to yarana iot guru.

Comments