Yarana Iot Guru
Published © MIT

🌐 Change WiFi Connection on ESP32 Without Re-uploading Code

Easily switch ESP32 Wi-Fi networks without re-uploading code. Perfect for portable IoT projects β€” YaranaIoT Guru DIY guide.

BeginnerShowcase (no instructions)8 hours55
🌐 Change WiFi Connection on ESP32 Without Re-uploading Code

Things used in this project

Software apps and online services

Arduino IDE
Arduino IDE

Story

Read more

Code

πŸ“„ Arduino Example Code β€” Wi-Fi Portal & Dynamic Connection

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

Preferences preferences;
WebServer server(80);

const char* ap_ssid = "ESP32_Config";
const char* ap_password = "12345678";

#define LED_PIN 2

void setup() {
  Serial.begin(115200);
  pinMode(LED_PIN, OUTPUT);
  
  preferences.begin("wifi", false);

  String ssid = preferences.getString("ssid", "");
  String password = preferences.getString("password", "");

  if(ssid != ""){
    WiFi.begin(ssid.c_str(), password.c_str());
    Serial.println("Trying to connect saved WiFi...");
    int tries = 0;
    while(WiFi.status() != WL_CONNECTED && tries < 20){
      delay(500);
      Serial.print(".");
      tries++;
    }
  }

  if(WiFi.status() != WL_CONNECTED){
    Serial.println("Starting AP for WiFi config");
    WiFi.softAP(ap_ssid, ap_password);
    server.on("/", handleRoot);
    server.on("/save", handleSave);
    server.begin();
  } else {
    Serial.println("Connected to WiFi!");
    Serial.println(WiFi.localIP());
  }
}

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

void handleRoot(){
  String html = "<form action='/save' method='POST'>"
                "SSID: <input name='ssid'><br>"
                "Password: <input name='password'><br>"
                "<input type='submit' value='Save'>"
                "</form>";
  server.send(200, "text/html", html);
}

void handleSave(){
  if(server.hasArg("ssid") && server.hasArg("password")){
    preferences.putString("ssid", server.arg("ssid"));
    preferences.putString("password", server.arg("password"));
    server.send(200, "text/html", "<h1>Saved! Reboot ESP32.</h1>");
    delay(2000);
    ESP.restart();
  }
}

Credits

Yarana Iot Guru
35 projects β€’ 0 followers
Yarana Iot Guru Yarana IoT Guru: Arduino, ESP32, GSM, NodeMCU & more. Projects, Tutorials & App Development. Innovate with us!
Thanks to YaranaIoT Guru.

Comments