#include <WiFi.h>
// WiFiClient client;
String ssid = "Wokwi-GUEST";
String password = "";
void connect_wifi() {
// Connect to Wi-Fi network
Serial.println("Connecting to wifi: " + String(ssid));
WiFi.begin(ssid, password);
int retries = 5;
while (WiFi.status() != WL_CONNECTED && retries) {
Serial.print(". ");
delay(1000);
retries--;
}
if (WiFi.status() == WL_CONNECTED) {
Serial.println("\nWiFi connected successfully!!");
} else {
Serial.println("\nWiFi connection failed\n");
}
}
void inputCreds() {
Serial.print("\nEnter SSID: ");
while (!Serial.available());
// Read the SSID from the serial port
ssid = Serial.readStringUntil('\n');
Serial.print("\"" + String(ssid) + "\"");
Serial.print("\nEnter password: ");
while (!Serial.available());
// Read the password from the serial port
password = Serial.readStringUntil('\n');
Serial.println("\"" + String(password) + "\"");
}
void handleWifi() {
Serial.println("Stored Wifi Credentials:-");
Serial.println("SSID: " + String(ssid) + ", Password: " + String(password) );
Serial.print("Do you want to change wifi credentials? ");
while (!Serial.available());
char command = Serial.read(); // Read the command character
while (Serial.available()) Serial.read();
Serial.println(command);
if (command == 'y') {
inputCreds();
}
// Call connect_wifi with the received SSID and password
connect_wifi();
}
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
WiFi.disconnect(); //Disconnect from previously connected wifi
Serial.println("\nWifi disconnected");
delay(200);
WiFi.mode(WIFI_STA); //STAtion mode: the ESP8266 connects to an access point
while (WiFi.status() != WL_CONNECTED) {
handleWifi();
}
}
void loop() {
Serial.println("Done");
delay(2000); // this speeds up the simulation
}